您的位置:首页 > 产品设计 > UI/UE

LeetCode 128. Longest Consecutive Sequence

2016-04-08 11:08 555 查看
/**
Given an unsorted array of integer, find the length of the longest
consecutive elements sequence.
For example:
Given [100, 4, 200, 1, 3, 2]
The longest consecutive element is [1, 2, 3, 4]. Return its length: 4
Your algorithm should run in O(n) complexity.
**/
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

int longConsecutive(vector<int>& nums) {
if(nums.size() <= 1) return nums.size();
unordered_set<int> data;
int maxLength = 0;
for(int i= 0; i < nums.size(); ++i) {
data.insert(nums[i]);
}
for(int i = 0; i < nums.size(); ++i) {
int target = nums[i];
int right = target + 1;
int left = target - 1;
int count = 1;
while(true) {
if(data.find(right) != data.end()) {
data.erase(right);
right = right + 1;
count++;
} else {
break;
}
}
while(true) {
if(data.find(left) != data.end()) {
data.erase(left);
left = left - 1;
count++;
} else {
break;
}
}
maxLength = max(maxLength, count);
}
return maxLength;
}

int main(void) {
vector<int> array;
array.push_back(100);
array.push_back(1);
array.push_back(2);
array.push_back(4);

int length = longConsecutive(array);
cout << length << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: