https://leetcode.com/problems/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, 5Example 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, 5Example 3:
Input: [1,2,3,4,4,5] Output: FalseNote:
- The length of the input is in range of [1, 10000]
搜索:
分为已满足要求的集合和未满足要求的集合
class Solution {
public:
bool isPossible(vector<int>& nums) {
vector<vector<int>> active;
vector<int> dead;
int st_act = 0, st_dea = 0;
int idx;
for(int cur : nums){
idx = st_act;
while(idx < active.size()){
if(active[idx].back() == cur-1) break;
else if(active[idx].back() < cur-1) return false;
++idx;
}
if(idx != active.size()){
if(active[idx].size() == 2){
st_act = idx+1;
dead.push_back(cur);
}else{
active[idx].push_back(cur);
}
}else{
idx = st_dea;
while(idx < dead.size()){
if(dead[idx] == cur-1) break;
++idx;
}
if(idx == dead.size()){
active.push_back(vector<int>());
active.back().push_back(cur);
}else{
dead[idx] = cur;
}
}
}
return st_act == active.size();
}
};
单趟搜索:
每一次只关心前一个数字加入后的结果
class Solution {
public:
bool isPossible(vector<int>& nums) {
int p1 = 0, p2 = 0, p3 = 0, c1, c2, c3;
int cur, pre = INT_MIN, cnt;
for(int i = 0; i < nums.size(); p1 = c1, p2 = c2, p3 = c3, pre = cur){
cnt = 0;
cur = nums[i];
while(i < nums.size() && nums[i] == cur){
++cnt;
++i;
}
if(cur == pre+1){
if((p1+p2) > cnt) return false;
c2 = p1;
c3 = p2+min(p3, cnt-p1-p2);
c1 = max(0, cnt-p1-p2-p3);
}else{
if(p1 || p2) return false;
c1 = cnt;
c2 = c3 = 0;
}
}
return p1 == 0 && p2 == 0;
}
};