Given an array nums sorted in ascending order, return true if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3.
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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/split-array-into-consecutive-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
使用两个map,一个record的map储存数字出现的个数。一个needs的map储存这个数字是否能连上上一个序列。
比如,123345,第一个遍历到1,那么就看23是否存在,存在的话,就把23的record计数减一,同时,把数字为4的坑位加一,说明如果来了一个四,是可以直接放进去的。
然后遍历到第二个3,发现3已经没坑了,因为前一个12的坑,已经被第一个3占了。那么3就要重新开始了,那现在就看4,5是否存在,如果存在,就把6的坑加一,45的record计数减一。
class Solution {
public boolean isPossible(int[] nums) {
Map<Integer, Integer> record = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
record.put(nums[i], record.getOrDefault(nums[i], 0 ) + 1);
}
Map<Integer, Integer> needs = new HashMap<>();
for (int num : nums) {
if (record.get(num) == 0) {
continue;
}
// needs大于0,说明有坑,直接放就好。同时把下一个空出的坑加一
if (needs.getOrDefault(num, 0) > 0) {
needs.put(num, needs.get(num) - 1);
needs.put(num + 1, needs.getOrDefault(num + 1, 0) + 1);
} else if (record.getOrDefault(num + 1, 0) > 0 && record.getOrDefault(num + 2, 0) > 0) {
// 如果没坑,就看它是否下两两个数字连续。连续就继续。
needs.put(num + 3, needs.getOrDefault(num + 3, 0) + 1);
record.put(num + 1, record.get(num + 1) - 1);
record.put(num + 2, record.get(num + 2) - 1);
} else return false;
record.put(num, record.get(num) - 1);
}
return true;
}
}