leetcode: Longest Consecutive Sequence

问题描述:

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.

原问题链接:https://leetcode.com/problems/longest-consecutive-sequence/

问题分析

  这个问题看起来确实有点难度,因为这个序列是没有排序的。如果我们需要去找它这里面元素能构成的最大序列,一种最简单的办法确实是对这个数组排序。但是一般来说,排序的时间复杂度就到了O(nlogn)了,而这里要求的时间复杂度为O(n)。所以上述的办法并不可行。

  既然上面方法不可行的话,我们就看看有没有别的办法。在数组里,我们可以将每个元素和它是否被访问过的标记放到一个Map<Integer, Boolean>里。这样所有的元素最开始对应的值都是false。而每次我们遍历元素数组的时候,就尝试从元素的两头分别递增和递减,如果递增或者递减后也有元素存在于map中,说明它们构成了一个连续的序列。在每次访问完一个元素之后,我们要将元素在map里对应的值设置为true,这样可以防止后面的元素再重复访问这个位置。我们就可以跳过一些不必要的比较。

  按照这个过程,我们整体的时间复杂度也可以降下来。详细的实现如下:

public class Solution {
    public int longestConsecutive(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int maxLen = 1;
        Map<Integer, Boolean> map = new HashMap<>();
        for(int i : nums) map.put(i, false);
        for(int i = 0; i < nums.length; i++) {
            int right = nums[i] + 1, n = nums[i], count = 0;
            while(map.containsKey(n) && !map.get(n)) {
                map.put(n, true);
                n--;
                count++;
            }
            while(map.containsKey(right) && !map.get(right)) {
                map.put(right, true);
                right++;
                count++;
            }
            maxLen = Math.max(maxLen, count);
        }
        return maxLen;
    }
}

猜你喜欢

转载自shmilyaw-hotmail-com.iteye.com/blog/2308732