题目:
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.
思路:先排序,然后再找最长连续序列
代码:
import java.lang.reflect.Array; import java.util.Arrays; public class Solution { public int longestConsecutive(int[] num) { if(num.length==0){ return 0; }if(num.length==1){ return 1; } Arrays.sort(num); int max = 1; int temp = 1; for(int i=1;i<num.length;i++){ if(num[i]-num[i-1]==1){ temp++; } else if(num[i]-num[i-1]==0){ continue; } else{ if(temp>max){ max=temp; } temp=1; } if(temp>max){ max = temp; } } return max; } }