# 算法作业系列(9)

## 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]

### 代码

``````#include<vector>
#include<iostream>
using namespace std;

class Solution {
public:
bool isPossible(vector<int>& nums) {
vector<vector<int> > set;
for (int i = 0; i < nums.size(); i++) {
int first = -1;
bool flag = false;
for (int j = 0; j < set.size(); j++) {
if (set[j].size() < 3 && set[j][set[j].size() - 1] + 1 < nums[i]) {
return false;
}
if (set[j].size() < 3 && set[j][set[j].size() - 1] + 1 == nums[i]) {
set[j].push_back(nums[i]);
first = -1;
flag = true;
break;
}
if (set[j].size() >= 3 && set[j][set[j].size() - 1] + 1 == nums[i] && first == -1) {
first = j;
}
}

if (first != -1) {
set[first].push_back(nums[i]);
continue;
}
if (flag == false) {
vector<int> tmp({nums[i]});
set.push_back(tmp);
}
}

for (int i = 0; i < set.size(); i++) {
if (set[i].size() <= 2) {
return false;
}
}
return true;
}
};``````