[LeetCode] 128. Longest Consecutive Sequence Java

题目:

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.

题意及分析:一个数组中连续的元素序列的长度。

用一个set来查找,首先第一次遍历数组将数组添加到set中,去除重复元素,第二次对数组中的每个数查找其最长的连续串,然后将遍历过的数从set中移除。这样每个数都被遍历了两次,时间复杂度为o(n).

代码:

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();

        for(int i=0;i<nums.length;i++){
            set.add(nums[i]);       //保持nums[i]中数的唯一性
        }
        int max = 0;
        for(int i=0;i<nums.length;i++){
            if(set.contains(nums[i])){
                int count = 1;
                set.remove(nums[i]);

                int low = nums[i]-1;
                while(set.contains(low)){
                    count++;
                    set.remove(low);
                    low--;
                }

                int high = nums[i]+1;
                while(set.contains(high)){
                    count++;
                    set.remove(high);
                    high++;
                }
                max = Math.max(max,count);
            }
        }
        return max;
    }
}

 

posted @ 2017-10-22 14:49  荒野第一快递员  阅读(319)  评论(0编辑  收藏  举报