[LeetCode] Divide Array in Sets of K Consecutive Numbers

1296. Divide Array in Sets of K Consecutive Numbers

Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers.

Return true if it is possible. Otherwise, return false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
bool isPossibleDivide(vector<int>& nums, int k) {
if(nums.size() % k) return false;
map<int, int> count;
for(auto n : nums) count[n]++;
while(!count.empty()) {
auto be = count.begin();
if(be->second) {
auto nxt = next(be);
for(int i = 1; i < k; i++,nxt++) {
if(nxt == count.end()) return false;
if(nxt->first != be->first + i) return false;
if(nxt->second < be->second)return false;
nxt->second -= be->second;

}

}
count.erase(be);

}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/divide-array-in-sets-of-k-consecutive-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.