Description
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个连续整数组成。返回是否可以做出这样的划分
问题分析
- freq保存数组元素对应个数
- appendfreq用来判断当前元素是否能够插入到一个已经构建好的序列末端
遍历nums,判断一个元素是否能够插入一个已经构建好的序列的末端,或者是否能作为新序列的起点,如果两者都不可以,返回false。
解法
class Solution {
public boolean isPossible(int[] nums) {
Map<Integer, Integer> freq = new HashMap<>(), appendfreq = new HashMap<>();
for (int i : nums) freq.put(i, freq.getOrDefault(i, 0) + 1);
for (int i : nums) {
//若当前元素个数为0, continue
if (freq.get(i) == 0) continue;
//大于0,表示当前元素可以插入到已经构建好的序列的末端
else if (appendfreq.getOrDefault(i, 0) > 0) {
appendfreq.put(i, appendfreq.get(i) - 1);
appendfreq.put(i + 1, appendfreq.getOrDefault(i + 1, 0) + 1);
}
//表示当前元素可以作为新序列的第一个元素
else if (freq.getOrDefault(i + 1, 0) > 0 && freq.getOrDefault(i + 2, 0) > 0) {
freq.put(i + 1, freq.get(i + 1) - 1);
freq.put(i + 2, freq.get(i + 2) - 1);
//注意这里,构建好一个序列,那么该序列最后一个元素+1一定能插入到序列末端
appendfreq.put(i + 3, appendfreq.getOrDefault(i + 3, 0) + 1);
}
else return false;
freq.put(i, freq.get(i) - 1);
}
return true;
}
}