659. 分割数组为连续子序列-中等-哈希表+小顶堆(贪心)
给你一个按升序排序的整数数组 num
(可能包含重复数字),请你将它们分割成一个或多个子序列,其中每个子序列都由连续整数组成且长度至少为3
。
如果可以完成上述分割,则返回true
;否则,返回 false
。
示例 1:
输入: [1,2,3,3,4,5]
输出: True
解释:
你可以分割出这样两个连续子序列 :
1, 2, 3
3, 4, 5
示例 2:
输入: [1,2,3,3,4,4,5,5]
输出: True
解释:
你可以分割出这样两个连续子序列 :
1, 2, 3, 4, 5
3, 4, 5
示例 3:
输入: [1,2,3,4,4,5]
输出: False
题解:
class Solution {
public boolean isPossible(int[] nums) {
Map<Integer, PriorityQueue<Integer>> map = new HashMap<>();
for (int i : nums) {
if (!map.containsKey(i)) {
map.put(i, new PriorityQueue<Integer>());
}
if (!map.containsKey(i-1)) {
map.get(i).add(1);
} else {
int length = map.get(i-1).poll();
if (map.get(i - 1).isEmpty()) {
map.remove(i - 1);
}
map.get(i).add(length+1);
}
}
for (Map.Entry<Integer, PriorityQueue<Integer>> entry : map.entrySet()) {
int length = entry.getValue().poll();
if (length < 3) {
return false;
}
}
return true;
}
}