---
# System prepended metadata

title: 1296. Divide Array in Sets of K Consecutive Numbers
tags: [Leetcode, TreeMap, Medium]

---

# 1296. Divide Array in Sets of K Consecutive Numbers
###### tags: `Leetcode` `Medium` `TreeMap`
Link: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
## 思路 $O(MlogM + MK)$
where $M$ is the number of different nums.
1. Count number of different number to a map $c$
2. Loop from the smallest number.
3. Everytime we meet a new num $i$, we cut off $i$ to $i+k-1$ from the counter.
for回圈要从后往前遍历 不然一上来就把map.get(it)改了
## Code
```java=
class Solution {
    public boolean isPossibleDivide(int[] nums, int k) {
        if(nums.length%k!=0) return false;
        Map<Integer, Integer> map = new TreeMap<>();
        for(int num:nums) map.put(num, map.getOrDefault(num,0)+1);
        for(int it:map.keySet()){
            if(map.get(it)>0){
                for(int i=k-1; i>=0; i--){
                    if(map.getOrDefault(it+i,0)<map.get(it)) return false;
                    map.put(it+i, map.get(it+i)-map.get(it));
                }
            }
        }
        return true;
    }
}
```