小米oj #4 最长连续数列
描述
输入一个乱序的连续数列,输出其中最长连续数列长度,要求算法复杂度为 O(n) 。
输入
54,55,300,12,56
输出
3
输入样例
100,4,200,1,3,2
54,55,300,12
1
5,4,3,2,1
1,2,3,4,5,6
输出样例
4
2
1
5
6
#include <bits/stdc++.h>
using namespace std;
int main()
{
// please write your code here
string str;
while(cin >> str){
istringstream iss(str);//#include<sstream>
string temp;
vector<int> vec;
map<int, int> m;
while(getline(iss, temp, ',')){//getline()第三个参数为分割符
vec.push_back(atoi(temp.c_str()));
m[atoi(temp.c_str())] = 0;//atoi()把数字字符串转换成int输出,atoi()的参数是 const char* ,因此对于一个字符串str我们必须调用 c_str()的方法把这个string转换成 const char*类型的
}
int max = 1;
sort(vec.begin(),vec.end());//排序
vector<int>::iterator it = vec.begin();
for(;it != vec.end(); it++){
int c = *it;
if(m[c] == 0){//判断数字重复
m[c] = 1;
if(m.count(c-1)){//前一个数字
m[c] += m[c-1];
}
if(m.count(c+1)){//后一个数字
m[c] += m[c+1];
}
}
max = max > m[c] ? max : m[c];
}
cout << max << endl;
}
return 0;
}