Descrition:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1,
2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
思路:
主要通過unordered_map()函數來記錄已經訪問的數,話說unordered_map()函數是真方便啊。
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<vector>
#include<string>
using namespace std;
class Solution{
public:
int MaxLength(const vector<int>& matrix) {
unordered_map<int, bool> used;
if (matrix.empty()) return 0;
for (auto i : matrix) used[i] = false;
int max_length = 0;
for (auto i:matrix){
if (used[i]) continue;
int length = 1;
used[i] = true;
//unordered_map<int,bool>
for (int x = i + 1; used.find(x) != used.end(); x++) {
used[x] = true;
length++;
}
//if (j == 0) continue;
for (int y = i - 1; used.find(y) != used.end(); y--) {
used[y] = true;
length++;
}
max_length = max(max_length,length);
}
return max_length;
}
};
int main(int argc, char** argv) {
vector<int> matrix;
int temp=0;
//string str;
//cin >> str;
cout << "Please input matrix:" << endl;
for (int i = 0; i < 10; i++) {
cin >> temp;
matrix.push_back(temp);
}
Solution test;
cout<<"Result:"<<test.MaxLength(matrix)<<endl;
//unordered_map<string, double> mymap = { {"wang",1},{"chao",2},{"long",3} };
//unordered_map<string, double>::iterator itr = mymap.find(str);
//
//if (itr != mymap.end())
// cout << itr->first << " is " << itr->second << endl;
//else
//{
// cout << "no found!" << endl;
//}
system("pause");
return 0;
}
結果如下: