🔒 문제 (LeetCode 128)

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.

Constraints:

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

 

🌊 입출력

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

 


 

🔑 해결

🌌 알고리즘 - 완전탐색

중복 포함된 배열을 고려하여 set을 사용

/**
 * @param {number[]} nums
 * @return {number}
 */
var longestConsecutive = function(nums) {
    if(!nums.length) return 0
    
    const set = new Set(nums)
    let max = 0
    
    for(const n of set) {
        if(set.has(n-1)) continue
        
        let currN = n
        let cnt = 1
        
        while(set.has(currN+1)) {
            currN++
            cnt++
        }
        max = Math.max(max, cnt)
    }

    return max
};

'코딩테스트 (JS) > 완전탐색' 카테고리의 다른 글

[JS] 놀이공원  (0) 2022.11.18
[JS] 방문 길이  (0) 2022.11.17
[JS] Max Points on a Line  (0) 2022.09.29
[JS] 자물쇠와 열쇠  (0) 2022.06.29
[JS] 기둥과 보 설치  (0) 2022.06.26

+ Recent posts