最长连续序列

给定一个未排序的整数数组,找出最长连续序列的长度。

说明

要求你的算法复杂度为O(n)

样例

给出数组[100, 4, 200, 1, 3, 2],这个最长的连续序列是 [1, 2, 3, 4],返回所求长度 4

解题

排序后比较简单,快排O(nlogn)

后面只需要O(n)的时间复杂度求解了

发现原数组里面有重复数字的时候,下面方法行不通了。

lintcode: 最长连续序列

 

public class Solution {
    /**
     * @param nums: A list of integers
     * @return an integer
     */
    public int longestConsecutive(int[] num) {
        // write you code here
        quickSort(num,0,num.length - 1);
        int maxLen = 1;
        int subLen = 1;
        if(num.length ==4){
            for(int i = 0;i< num.length;i++){
                System.out.print(num[i] + "\t");
            }
        }
        for(int i = 0;i<= num.length-2 ;i++){
            if(num[i] + 1 ==num[i+1]){
                subLen++;
            }else{
                subLen = 1;
                
            }
            maxLen = Math.max(maxLen,subLen);
        }
        return maxLen;
    }
    
    public void quickSort(int[] A,int low ,int high){
        if(low>= high)
            return;
        int i = low;
        int j = high;
        int tmp  = A[low];
        while(i<j){
            while(i<j && A[j] > tmp)
                j--;
            if(i<j){
                A[i] = A[j];
                i++;
            }
            
            while(i<j && A[i]<= tmp)
                i++;
            if(i<j){
                A[j] = A[i];
                j--;
            }
            
        }
        A[i] = tmp;
        quickSort(A,low,i-1);
        quickSort(A,i+1,high);
    }
}
View Code

相关文章: