【貪心】B039_LC_劃分數組爲連續數字的集合(排序 + map)

一、Problem

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.

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

二、Solution

方法一:排序

  • 用 map 統計數字的頻次,並對數組 A 排序,排序的好處是在枚舉完一個以 A[i] 爲開頭且大小爲 k 的區間後,可以立馬得到一個比 A[i] 大且最小的數字。
  • 貪心思路:如果一個一 A[i] 爲開頭的區間能組成大小爲 k 的連續數集合,那麼在 map 中一定可以找到 [A[i]+1,A[i]+2,...,A[i]+k][A[i]+1, A[i]+2,..., A[i]+k] $ 的全部數字。

這題做得比較急:導致使用 A[i] 後忘記刪去 A[i] 的使用頻次了,浪費了一點時間…

class Solution {
    public boolean isPossibleDivide(int[] A, int k) {
        int n = A.length;
        if (n % k != 0)
            return false;
        Map<Integer, Integer> m = new HashMap<>();
        Arrays.sort(A);
        for (int i : A)  m.put(i, m.getOrDefault(i, 0) + 1);
        int cnt = 0, need = n / k;
        
        for (int i : A) {
            int fr = m.get(i);
            if (fr == 0)
                continue;
            m.put(i, fr-1);
            for (int j = 1; j < k; j++) {
                int freq = m.getOrDefault(i+j, 0);
                if (freq == 0)
                    return false;
                m.put(i+j, freq - 1);
            }
            if (++cnt == need)
                return true;
        }
        return true;
    }
}

複雜度分析

  • 時間複雜度:O(nlogn)O(nlogn)
  • 空間複雜度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章