Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode 128. 最长连续序列 #12

Open
yinxin630 opened this issue May 25, 2019 · 0 comments
Open

LeetCode 128. 最长连续序列 #12

yinxin630 opened this issue May 25, 2019 · 0 comments
Labels

Comments

@yinxin630
Copy link
Owner

题目

https://leetcode-cn.com/problems/longest-consecutive-sequence/

思路

  1. 使用 hash 表, map[n] 表示以数字 n 为端点的序列长度
  2. map[n] = 1 + map[n - 1] + map[n + 1]. map[n - 1] 是前一个序列, map[n + 1] 是后一个序列, 前序列和后序列均可为空(长度 = 0)
  3. 如果 map[n - 1] 不为空, 则更新 map[n - map[n - 1]] = map[n], 即前序列的左端点
  4. 如果 map[n + 1] 不为空, 则更新 map[n + map[n + 1]] = map[n], 即后序列的右端点

代码

/**
 * @param {number[]} nums
 * @return {number}
 */
var longestConsecutive = function(nums) {
    const map = {};
    let max = 0;
    for (let i = 0; i < nums.length; i++) {
        if (map[nums[i]]) {
            continue;
        }

        map[nums[i]] = 1 + (map[nums[i] - 1] || 0) + (map[nums[i] + 1] || 0);

        if (map[nums[i] - 1]) {
            map[nums[i] - map[nums[i] - 1]] = map[nums[i]]
        }

        if (map[nums[i] + 1]) {
            map[nums[i] + map[nums[i] + 1]] = map[nums[i]]
        }

        max = Math.max(max, map[nums[i]]);
    }

    return max;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant