一、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] 後忘記刪去 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;
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,