题目描述:
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
Constraints:
1 <= nums.length <= 10000
class Solution {
public:
bool isPossible(vector<int>& nums) {
unordered_map<int,int> count;
// tail的key对应数字,value对应存在多少个序列可以以该数字结尾
unordered_map<int,int> tail;
for(int num:nums) count[num]++;
for(int num:nums)
{
// count为零说明已经被其他序列用掉了,不用再考虑
if(count[num]==0) continue;
// 先考虑当前数字是否能作为已有序列的结尾,这样避免创建新的序列
if(tail[num]>0)
{
tail[num]--;
count[num]--;
tail[num+1]++;
}
// 否则以当前数字为起点创建新序列,并保证序列长度最小为3
else if(count[num+1]>0&&count[num+2]>0)
{
count[num]--;
count[num+1]--;
count[num+2]--;
tail[num+3]++;
}
else return false;
}
return true;
}
};