Description
Given an array of integers nums and a positive integer k, find whether it’s possible to divide this array into sets of k consecutive numbers
Return True if its possible otherwise return False.
Example
Example 1:1
2
3Input: nums = [1,2,3,3,4,4,5,6], k = 4
Output: true
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].
Example 2:1
2
3Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output: true
Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].
Example 3:1
2Input: nums = [3,3,2,2,1,1], k = 3
Output: true
Example 4:1
2
3Input: nums = [1,2,3,4], k = 3
Output: false
Explanation: Each array should be divided in subarrays of size 3.
Constraints:1
2
31 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
1 <= k <= nums.length
Note: This question is the same as 846: https://leetcode.com/problems/hand-of-straights/
Solution
Solution 1: Basic
- Count number of different cards to a map c
- Loop from the smallest card number.
- Everytime we meet a new card i, we cut off i - i + k - 1 from the counter.
- Time Complexity:
- Space Complexity:
1 | class Solution { |
Solution 2: Improved
- Count number of different cards to a map c
- Cur represent current open straight groups.
- In a deque start, we record the number of opened a straight group.
- Loop from the smallest card number.
1
2
3
4
5
6
7
8
9
10
11For example, A = [1,2,3,2,3,4], k = 3
We meet one 1:
opened = 0, we open a new straight groups starting at 1, push (1,1) to start.
We meet two 2:
opened = 1, we need open another straight groups starting at 1, push (2,1) to start.
We meet two 3:
opened = 2, it match current opened groups.
We open one group at 1, now we close it. opened = opened - 1 = 1
We meet one 4:
opened = 1, it match current opened groups.
We open one group at 2, now we close it. opened = opened - 1 = 0 - return if no more open groups.
- Time Complexity:
- Space Complexity:
1 | class Solution { |
Solution 3: Fastest
- Time Complexity: , overall each element will be visited twice.
- Space Complexity:
1 | class Solution { |