leetcode: longestConsecutive

 1 int longestConsecutive(const vector<int> &num) {
 2     unordered_map<int, int> hash;
 3     for (int i=0; i<num.size(); ++i) 
 4         hash[num[i]] = 1;
 5 
 6     int ans=0;
 7     for (int i=0; i<num.size(); ++i) {
 8         unordered_map<int, int>::iterator it = hash.find(num[i]+1);;
 9         for (int j=num[i]+1; it!=hash.end(); it=hash.find(++j)) {
10             hash[num[i]] += it->second;
11             hash.erase(it);
12         }
13         ans = max(ans, hash[num[i]]);
14     }
15     return ans;
16 }

 

posted @ 2013-04-28 14:09  caijinlong  阅读(151)  评论(0编辑  收藏  举报