- set 会自动排序。
- 使用ans = 1, q =1 以及 比一个删除一个得方式,进行判断最长子序列。
- 其余看注释。
class Solution {
public:
/**
* max increasing subsequence
* @param arr int整型vector the array
* @return int整型
*/
int MLS(vector<int>& arr) {
// write code here
if(!arr.size()){
return 0;
}
set<int> s;//默认有序
for(auto x: arr){
s.insert(x);
}
int ans =1, q = 1, pre = *s.begin();// q相当与很多队列得起始点得计数
s.erase(pre);//set 删除元素
while(s.size()){
int now = *s.begin();
s.erase(now);//删除,为下一次比较做预备
if(pre == now -1){//连续
if(ans<++q) ans = q;// 先加加,然后直接赋值即可。
}else q = 1;//新的队列
pre = now;//这样就可以对应pre是那个删掉的元素
}
return ans;
}
};