Wednesday, July 6, 2016

128. Longest Consecutive Sequence

The idea is to set up a hashmap for all numbers first. And then scan all numbers again and try to find the first number that is not consecutive, i.e. nums[i]-1 is not in the hashmap. After that, count the consecutive numbers from that number on, and save the largest length until now.

1:  class Solution {  
2:  public:  
3:    int longestConsecutive(vector<int>& nums) {  
4:      unordered_map<int, int> mapping;  
5:      int maxLen = 0;  
6:      for (int i = 0; i < nums.size(); i++) {  
7:        mapping[nums[i]] = 1;  
8:      }  
9:      for (int i = 0; i < nums.size(); i++) {  
10:        if (mapping.find(nums[i]-1) == mapping.end()) {  
11:          int n = nums[i]+1;  
12:          while (mapping.find(n) != mapping.end()) {  
13:            n++;  
14:          }  
15:          maxLen = max(maxLen, n-nums[i]);  
16:        }  
17:      }  
18:      return maxLen;  
19:    }  
20:  };  

No comments:

Post a Comment