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.
public class Solution { public int longestConsecutive(int[] num) { if(num==null || num.length<1 ) return 0; int longest = 1; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Set<Integer> set = new HashSet<Integer>(); for(int i=0; i<num.length; i++) { int x = num[i]; if(set.contains(x) ) continue; set.add(x); int min = x, max = x; if( map.containsKey(x+1) ) { max = map.get(x+1); map.remove(map.get(x+1) ); map.remove(x+1); } if( map.containsKey(x-1) ) { min = map.get(x-1); map.remove(map.get(x-1) ); map.remove(x-1); } map.put(min, max); map.put(max, min); longest = longest > max-min+1 ? longest : max-min+1; } return longest; } }
class Solution { public: int longestConsecutive(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function unordered_map<int,int> mymap; unordered_set<int> unique; int max = 0; for(int i=0; i<num.size(); i++) { if(unique.find(num[i])!=unique.end()) { continue; } else { unique.insert(num[i]); } int left=num[i], right = num[i]; if(mymap.find(left-1)!=mymap.end() && mymap[left-1] <= left-1) { //should be left-1 left = mymap[left-1]; } if(mymap.find(right+1)!=mymap.end() && mymap[right+1] >= right+1) { //should be right+1 right = mymap[right+1]; } mymap[left] = right; //don't forget put these into the map. mymap[right] = left; max = max > (right-left+1) ? max : (right-left+1); //do not need to iterate map again. use var to record max value. } return max; } };
O(nlogn) algorithm, because of sorting.
class Solution { public: int longestConsecutive(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function //Given [100, 4, 200, 1, 3, 2], //The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. sort(num.begin(), num.end() ); int longest = 1; int cur=1; for(int i=1; i<num.size(); i++) { if(num[i]==num[i-1]+1) { ++cur; longest = longest>=cur? longest : cur; } else if(num[i]==num[i-1]) { continue; } else { cur=1; } } return longest; } };