Longest Consecutive Sequence 分类: Leetcode(线性表) 2015-02-04 09:54 55人阅读 评论(0) 收藏
Longest Consecutive Sequence
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.
对于线性表的题目,如果要求复杂度是O(n)的,我只能说,请考虑hash!!!!!!!!!!!!!!!!!!!!!!!
class Solution { public: int longestConsecutive(vector<int> &num) { unordered_map<int, bool> used; int i,j; for(i = 0; i < num.size(); i++){ used[num[i]] = false; } int longest = 0; for(i =0; i < num.size(); i++){ if (used[num[i]]) continue; int length = 1; used[num[i]] = true; for(j = num[i] + 1; used.find(j) != used.end(); ++j){ used[j] = true; ++length; } for(j = num[i]-1; used.find(j) != used.end(); --j){ used[j] = true; ++length; } longest = max(longest, length); } return longest; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。