没有看题解,算是卡样例吧,样例多一点就写不出来了
#include <iostream>
#include "vector"
#include "algorithm"
using namespace std;
bool is_allsame(vector<int> &v) {
int first = v[0];
for (auto &number: v) {
if (first != number) {
return false;
}
}
return true;
}
//[9,1,4,7,3,-1,0,5,8,-1,6]
int check(vector<int> &res) {
int length = 0, length_two = 0, len = 0;
int max, min;
vector<int> v;
if (res.empty()) return 0;
if (res.size() == 1) return 1;
if(is_allsame(res)) return 1;
sort(res.begin(), res.end());
min = res[0];
for (int i = 1; i < res.size(); ++i) {
if (min == res[i] - 1) {
length++;
min = res[i];
if (length > len) {
len = length;
v.push_back(len + 1);
}
}
if (min < res[i] - 1) {
length_two++;
length = 0;
min = res[i];
int len2;
if (length_two > len2) {
length_two = 0;
v.push_back(length_two + 1);
}
}
}
if (v.empty()) return 1;
return *max_element(v.begin(), v.end());
}
int main() {
vector<int> f = {-6,-1,-1,9,-8,-6,-6,4,4,-3,-8,-1};
int length = check(f);
cout << length << endl;
return 0;
}
最后发现用hash更快,当时自己能力有限就用了这种常规的!