[LeetCode] 128. Longest Consecutive Sequence

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

You must write an algorithm that runs in O(n) time.

Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Example 3:
Input: nums = [1,0,1,2]
Output: 3

Constraints:
0 <= nums.length <= 105
-109 <= nums[i] <= 109

最长连续序列。

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-consecutive-sequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

思路是在遍历数组的时候,第一次遍历先用 hashset 存住所有的元素。再遍历第二次,第二次遍历的时候,找每一个元素的 left (num - 1) 和 right (num + 1),若找到,就在 hashset 中移除,同时移动 left 和 right 的位置。最终最长的子序列长度为 right - left - 1。

复杂度

时间O(n)
空间O(n)

代码

Java实现

class Solution {
    public int longestConsecutive(int[] nums) {
        // corner case
        if (nums == null || nums.length == 0) {
            return 0;
        }

        // normal case
        int res = 0;
        HashSet<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }
        for (int i = 0; i < nums.length; i++) {
            int down = nums[i] - 1;
            while (set.contains(down)) {
                set.remove(down);
                down--;
            }
            int up = nums[i] + 1;
            while (set.contains(up)) {
                set.remove(up);
                up++;
            }
            res = Math.max(res, up - down - 1);
        }
        return res;
    }
}

JavaScript实现

/**
 * @param {number[]} nums
 * @return {number}
 */
var longestConsecutive = function(nums) {
    let res = 0;
    let set = new Set();
    for (let i = 0; i < nums.length; i++) {
        let num = nums[i];
        set.add(num);
    }
    for (let i = 0; i < nums.length; i++) {
        let cur = nums[i];
        let down = cur - 1;
        while (set.has(down)) {
            set.delete(down);
            down--;
        }
        let up = cur + 1;
        while (set.has(up)) {
            set.delete(up);
            up++;
        }
        res = Math.max(res, up - down - 1);
    }
    return res;
};
posted @ 2019-10-09 11:11  CNoodle  阅读(500)  评论(0)    收藏  举报