Skip to content

Instantly share code, notes, and snippets.

@daifu
Created March 5, 2013 08:21
Show Gist options
  • Select an option

  • Save daifu/5088769 to your computer and use it in GitHub Desktop.

Select an option

Save daifu/5088769 to your computer and use it in GitHub Desktop.
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
/*
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.
*/
public class Solution {
public int longestConsecutive(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
if(num.length == 1) return 1;
Arrays.sort(num);
int cur_max = 1;
int max = 0;
int end = num.length - 1;
for(int i = 0; i < end; i++) {
if((num[i+1] - num[i]) == 1) {
cur_max++;
} else if ((num[i+1] - num[i]) != 0) {
cur_max = 1;
}
if(cur_max > max) {
max = cur_max;
}
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment