Leetcode Longest Consecutive Sequence, Feb 143855 / 11012
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.
思路:信息只要存储在区间的两个端点就行了。所以建立一个map,对于端点来说,值是对应区间的长度。每次进来一个新数i, 检查i-1, i+1是否在map中,如果是,则更新相应的端点值就行了。同时更新最长长度候选值。
ps: 不写code好像也没多久啊,竟然就手生了。。看来还是应该每天练一道。
- int longestConsecutive(vector<int> &num) {
- unordered_map<int,int> v;
- int res = 1;
- for(int i = 0; i < num.size(); i++){
- if(v.find(num[i]) != v.end() ) continue;
- v[num[i]] = 1;
- if(v.find(num[i]-1) != v.end()) v[num[i]] += v[num[i]-1];
- if(v.find(num[i]+1) != v.end()) v[num[i]] += v[num[i]+1];
- if(v.find(num[i]-1) != v.end()) v[num[i] - v[num[i] - 1] ] = v[num[i]];
- if(v.find(num[i]+1) != v.end()) v[num[i] + v[num[i] + 1] ] = v[num[i]];
- res = max(res, v[num[i]]);
- }
- return res;
- }
No comments:
Post a Comment