[菜鸟刷题]算法——最长连续序列

72 阅读1分钟

128. 最长连续序列

image.png

【题解】哈希表思路和算法

  • 首先设置Set枚举 numsSet,使用Set可以对原数组去重,并且可以提供查找方法快速判断并获取元素
  • 要获得连续序列,那么这个序列的第一个数x一定在numsSet中,且x-1一定不在numsSet
  • numsSet中查找不存在 x-1x值,并循环计算x++ 是否在numsSet
  • 循环过程中保留每次循环的最大次数,即为最长的连续序列的长度

【代码】

/**
 * @param {number[]} nums
 * @return {number}
 */
var longestConsecutive = function(nums) {
  let numsSet = new Set()
  for (let i of nums) {
    numsSet.add(i)
  }
  let ret = 0
  
  for(let num of numsSet) {
    if (!numsSet.has(num - 1)) {
      let currentNum = num
      let currentLen = 1

      while (numsSet.has(currentNum + 1)) {
        currentNum += 1
        currentLen += 1
      }
      ret = Math.max(ret, currentLen)
    }
  }

  return ret
};