码迷,mamicode.com
首页 > 其他好文 > 详细

1296. Divide Array in Sets of K Consecutive Numbers

时间:2020-01-18 10:37:01      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:empty   discuss   shm   全局   tps   each   sub   Plan   oss   

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

标签:empty   discuss   shm   全局   tps   each   sub   Plan   oss   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12208111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!