Split Array into Consecutive Subsequences
问题:
You are given an integer array sorted in ascending order (may contain duplicates), you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split.
Example 1:
Input: [1,2,3,3,4,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3 3, 4, 5
Example 2:
Input: [1,2,3,3,4,4,5,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3, 4, 5 3, 4, 5
Example 3:
Input: [1,2,3,4,4,5] Output: False
Note:
- The length of the input is in range of [1, 10000]
解决:
① 给定的整数数组按照升序排列(可能包含重复项),需要将它们分成几个子序列,每个子序列至少包含3个连续的整数。 返回是否可以做出这样的分割。
1. 遍历数组,得到数组中所有元素的出现次数;
2. 再次遍历数组,并且对于每个元素,要么查看它是否可以附加到先前构建的连续序列,要么是否可以是新的连续序列的开始。 如果两个都不是真的,那我们就返回假。
class Solution { //108ms
public boolean isPossible(int[] nums) {
Map<Integer,Integer> frequenceMap = new HashMap<>();
Map<Integer,Integer> appendMap = new HashMap<>();
for (int n : nums){
frequenceMap.put(n,frequenceMap.getOrDefault(n,0) + 1);
}
for (int n : nums){
if (frequenceMap.get(n) == 0) continue;
else if (appendMap.getOrDefault(n,0) > 0){
appendMap.put(n,appendMap.get(n) - 1);
appendMap.put(n + 1,appendMap.getOrDefault(n + 1,0) + 1);
}else if (frequenceMap.getOrDefault(n + 1,0) > 0 && frequenceMap.getOrDefault(n + 2,0) > 0){
frequenceMap.put(n + 1,frequenceMap.get(n + 1) - 1);
frequenceMap.put(n + 2,frequenceMap.get(n + 2) - 1);
appendMap.put(n + 3,appendMap.getOrDefault(n + 3,0) + 1);
}else {
return false;
}
frequenceMap.put(n,frequenceMap.get(n) - 1);
}
return true;
}
}
② 在discuss中看到的解法。。。
class Solution {//16ms public boolean isPossible(int[] nums) { int pre = Integer.MIN_VALUE, p1 = 0, p2 = 0, p3 = 0; int cur = 0, cnt = 0, c1 = 0, c2 = 0, c3 = 0; for (int i = 0; i < nums.length; pre = cur, p1 = c1, p2 = c2, p3 = c3) { for (cur = nums[i], cnt = 0; i < nums.length && cur == nums[i]; cnt++, i++); if (cur != pre + 1) { if (p1 != 0 || p2 != 0) return false; c1 = cnt; c2 = 0; c3 = 0; } else { if (cnt < p1 + p2) return false; c1 = Math.max(0, cnt - (p1 + p2 + p3)); c2 = p1; c3 = p2 + Math.min(p3, cnt - (p1 + p2)); } } return p1 == 0 && p2 == 0; } }