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].

思路:這跟hand of straights 一模一樣,代碼都一樣。就是統計頻率之後,用pq sort一下,然後拿出最小的組成k個size的順子,如果沒有牌或者頻率少於num,直接return false;

class Solution {
    public boolean isPossibleDivide(int[] nums, int k) {
        if(nums == null || nums.length == 0) {
            return false;
        }
        HashMap<Integer, Integer> countmap = new HashMap<Integer, Integer>();
        for(int num: nums) {
            countmap.put(num, countmap.getOrDefault(num, 0) + 1);
        }
        
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
        pq.addAll(countmap.keySet());
        
        while(!pq.isEmpty()) {
            int start = pq.poll();
            int num = countmap.get(start);
            if(num > 0) {
                for(int i = 0; i < k; i++) {
                    if(!countmap.containsKey(start + i) || countmap.get(start + i) < num) {
                        return false;
                    }
                    countmap.put(start + i, countmap.get(start + i) - num);
                }
            }
        }
        return true;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章