lintcode-medium-Longest Consecutive Sequence

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Longest Consecutive Sequence相关的知识,希望对你有一定的参考价值。

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

 

Clarification

Your algorithm should run in O(n) complexity.

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 {
    /**
     * @param nums: A list of integers
     * @return an integer
     */
    public int longestConsecutive(int[] num) {
        // write you code here
        
        if(num == null || num.length == 0)
            return 0;
        
        HashSet<Integer> set = new HashSet<Integer>();
        
        for(int i = 0; i < num.length; i++)
            set.add(num[i]);
        
        int result = 1;
            
        for(int i = 0; i < num.length; i++){
            int left = num[i] - 1;
            int right = num[i] + 1;
            int max = 1;
            
            while(set.contains(left)){
                set.remove(left);
                left--;
                max++;
            }
            while(set.contains(right)){
                set.remove(right);
                right++;
                max++;
            }
            
            result = Math.max(max, result);
        }
        
        return result;
    }
}

 

以上是关于lintcode-medium-Longest Consecutive Sequence的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-medium-Longest Palindromic Substring

SQL CTE性能是否取决于声明顺序?

C/C++ ceil 函数

C/C++ floor 函数

C语言数组问题?

关于c++/c