1296. Divide Array in Sets of K Consecutive Numbers

Posted wentiliangkaihua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = 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?

以上是关于1296. Divide Array in Sets of K Consecutive Numbers的主要内容,如果未能解决你的问题,请参考以下文章

153. Find Minimum in Rotated Sorted Array (Array; Divide-and-Conquer)

81. Search in Rotated Sorted Array II (Array; Divide-and-Conquer)

154. Find Minimum in Rotated Sorted Array II (Array; Divide-and-Conquer)

[Algorithms] Divide and Recurse Over an Array with Merge Sort in JavaScript

[Leetcode] Heap, Divide and conquer--215. Kth Largest Element in an Array

[LeetCode] 1675. Minimize Deviation in Array