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.

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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: true

Example 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
class Solution {
    public boolean isPossibleDivide(int[] nums, int k) {
        boolean res = false;
        int l = nums.length;
        if(l % k != 0) return res;
        Map<Integer, Integer> map = new HashMap();
        PriorityQueue<Integer> q = new PriorityQueue();
        for(int i: nums){
            map.put(i, map.getOrDefault(i, 0)+1);          
        }
        for(int i: map.keySet()) q.offer(i);
        while(!q.isEmpty()){
            int cur = q.poll();
            if(map.get(cur) == 0) continue;
            int times = map.get(cur);
            for(int i = 0; i < k; i++){
                if(!map.containsKey(cur + i) || map.get(cur + i) < times) return false;
                map.put(cur + i, map.get(cur + i) - times);
            }
            l -= k * times;
        }
        return l == 0;
    }
}

https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/discuss/457687/Java-Map-and-PriorityQueue-O(dlgd)

首先判断有没有k倍的元素,然后用map记录每个数出现的数量,然后用pq记下出现的数字,并用全局变量l记录数组长度。

先拿出一个key,如果对应的value==0就跳过,否则就用times出现的数量。

从0到k-1循环,如果没有cur+i或者cur+i剩余数量少于times说明必不可能成功,return false,更新map中每个key的value

更新剩余长度l

判断l==0?

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄