LeetCode-1296. Divide Array in Sets of K Consecutive Numbers

网友投稿 599 2022-08-25

LeetCode-1296. Divide Array in Sets of K Consecutive Numbers

LeetCode-1296. Divide Array in Sets of K Consecutive Numbers

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 = 4Output: trueExplanation: 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 = 3Output: trueExplanation: 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 = 3Output: true

Example 4:

Input: nums = [1,2,3,4], k = 3Output: falseExplanation: 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​​

题解:

排序后查找。

class Solution {public: bool isPossibleDivide(vector& nums, int k) { if (nums.size() % k != 0) { return false; } sort(nums.begin(), nums.end()); unordered_map m; for (int i = 0; i < nums.size(); i++) { m[nums[i]]++; } for (int i = 0; i < nums.size(); i++) { if (m[nums[i]] > 0) { m[nums[i]]--; for (int j = 1; j < k; j++) { if (m[nums[i] + j] > 0) { m[nums[i] + j]--; } else { return false; } } } } return true; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-543. Diameter of Binary Tree
下一篇:LeetCode-875. Koko Eating Bananas
相关文章

 发表评论

暂时没有评论,来抢沙发吧~