1. 程式人生 > >leetCode練習(128)

leetCode練習(128)

題目:Longest Consecutive Sequence

難度:hard

問題描述:

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.

解題思路:

很容易的一道題,不知道為啥是hard~ 先將陣列排序成[1,2,3,4,100,200],然後遍歷找到最大連續組即可。其中注意重複的數要剔除即可。

程式碼如下:

public class Solution {
    public int longestConsecutive(int[] nums) {
        if(nums==null) return 0;
		int len=nums.length;
		if(len<=1)return len;
        Arrays.sort(nums);
        
        int res=1;
        int temp=nums[0];
        int cha;
        int count=1;
        for(int i=1;i<len;i++){
        	cha=nums[i]-temp;
        	if(cha==0) continue;
        	if(cha==1){
        		temp++;
        		count++;
        	}else{
        		res=res>count?res:count;
        		
        		count=1;
        		temp=nums[i];
        	}
        } 
        res=res>count?res:count;
        return res;
    }
}