leetcode-题6--Longest Consecutive Sequence
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int a[5] = { 1,3,5,6,7 }; int cnt = 1; int max = 1; sort(a, a + 5); for (int i = 1; i < 5; ++i) { if (a[i] == a[i - 1] + 1) { cnt++; max = max > cnt ? max : cnt; } else { cnt = 1; max = 1; } } cout << max << endl; system("pause"); return 0; }
解法2:
#include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main() { int a[6] = { 100,2,3,200,4,5 }; unordered_map<int, bool>nums; for (auto i : a) nums[i] = false; int len = 1; int m = 1; for (auto i : a) { if (nums[i])continue; for (int j = i + 1; nums.find(j) != nums.end(); ++j) { len++; nums[j] = true; } for (int j = i - 1; nums.find(j) != nums.end(); --j) { len++; nums[j] = true; } m = max(len, m); len = 1; } cout << m << endl; system("pause"); return 0; }