• 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?

  • 相关阅读:
    codechef May Challenge 2016 CHSC: Che and ig Soccer dfs处理
    codechef May Challenge 2016 FORESTGA: Forest Gathering 二分
    codechef May Challenge 2016 LADDU: Ladd 模拟
    tp5 whereOr
    Null
    验证消息是否来自微信
    layer使用注意事项
    laravel 查询
    laravel form表单提交
    ajax上传文件
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12208111.html
Copyright © 2020-2023  润新知