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 1:
Input: 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:
Input: 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:
Input: nums = [3,3,2,2,1,1], k = 3 Output: trueExample 4:
Input: nums = [1,2,3,4], k = 3 Output: false Explanation: Each array should be divided in subarrays of size 3.
Constraints:
1 <= 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/
划分数组为连续数字的集合。
题意跟846题真的是一模一样,那么思路也就请参见846题吧。
时间O(nlogn)
空间O(n)
Java实现
1 class Solution { 2 public boolean isPossibleDivide(int[] nums, int k) { 3 // corner case 4 if (nums.length % k != 0) { 5 return false; 6 } 7 8 // normal case 9 HashMap<Integer, Integer> map = new HashMap<>(); 10 for (int num : nums) { 11 map.put(num, map.getOrDefault(num, 0) + 1); 12 } 13 Arrays.sort(nums); 14 for (int i = 0; i < nums.length; i++) { 15 if (map.get(nums[i]) == 0) { 16 continue; 17 } 18 int cur = nums[i]; 19 int end = nums[i] + k; 20 while (cur < end) { 21 int count = map.getOrDefault(cur, 0); 22 if (count == 0) { 23 return false; 24 } 25 map.put(cur, map.get(cur) - 1); 26 cur++; 27 } 28 } 29 return true; 30 } 31 }
相关题目
1296. Divide Array in Sets of K Consecutive Numbers