Monday, June 17, 2013

Longest Consecutive Sequence(C++ code)

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好像也没多久啊,竟然就手生了。。看来还是应该每天练一道。



  1. int longestConsecutive(vector<int> &num) {  
  2.   
  3.       unordered_map<int,int> v;  
  4.   
  5.       int res = 1;  
  6.   
  7.       for(int i = 0; i < num.size(); i++){  
  8.   
  9.          if(v.find(num[i]) != v.end() ) continue;  
  10.   
  11.          v[num[i]] = 1;  
  12.   
  13.          if(v.find(num[i]-1) != v.end()) v[num[i]] +=  v[num[i]-1];  
  14.   
  15.          if(v.find(num[i]+1) != v.end()) v[num[i]] +=  v[num[i]+1];  
  16.   
  17.          if(v.find(num[i]-1) != v.end()) v[num[i] - v[num[i] - 1] ] = v[num[i]];  
  18.   
  19.          if(v.find(num[i]+1) != v.end()) v[num[i] + v[num[i] + 1] ] = v[num[i]];  
  20.   
  21.          res = max(res, v[num[i]]);  
  22.   
  23.       }  
  24.   
  25.      return res;  
  26.   
  27.   }  

No comments:

Post a Comment