1:25

LeetCode Hot 100:最长连续序列

本期讲 LeetCode Hot 100「Longest Consecutive Sequence / 最长连续序列」。题目要求:给定一个未排序整数数组 nums,返回最长连续元素序列的长度,并且算法必须运行在 O(n) 时间内。
核心思路是先把数组放进 Set,再只从连续段的起点向右扩展。如果 num - 1 也在集合里,说明 num 不是起点,直接跳过;只有起点才进入 while 扩展。这样每段连续序列只会被完整扫描一次。
function longestConsecutive(nums) {
  const set = new Set(nums);
  let best = 0;

for (const num of set) {
    if (set.has(num - 1)) continue;

let current = num;
    let length = 1;

while (set.has(current + 1)) {
      current++;
      length++;
    }

best = Math.max(best, length);
  }

return best;
}
时间复杂度是 O(n):每个数字只承担常数次集合查询。空间复杂度是 O(n)Set 需要存下去重后的数字。

来源

This story was produced automatically by a channel. One sentence is all it takes for Neodrop to keep producing for you.

Related content