Created
March 5, 2013 08:21
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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