๐Ÿค– ์•Œ๊ณ ๋ฆฌ์ฆ˜

[leetcode] 128. Longest Consecutive Sequence ์‹œ๊ฐ„๋ณต์žก๋„ O(n) ํ’€์ด, ํ•ด์„ค (python)

ttoance 2023. 10. 21. 06:04

๋ฌธ์ œ ๋งํฌ

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

 

Longest Consecutive Sequence - LeetCode

Can you solve this real interview question? 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:

leetcode.com

 

1์ฐจ ํ’€์ด

O(n)์„ ๋ชฉํ‘œ๋กœ ํ’€๋‹ค๊ฐ€, O(nlogn)์œผ๋กœ ๋น ์ ธ๋ฒ„๋ฆฐ ํ’€์ด์ด๋‹ค.

์ค‘๊ฐ„์— ์ •๋ ฌ์„ ์ง„ํ–‰ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— O(nlogn), ๊ทธ ํ›„ for๋ฌธ์—์„œ O(n) ์ด O(n) + O(nlogn) = O(nlogn)์ด ๋˜์—ˆ๋‹ค. 

 

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
    
        result = 0 
        prev = None
        tempCount = 1
        
        nums.sort()
        for n in nums:
            # prev ์ด ์ดˆ๊ธฐํ™”๋˜์–ด์žˆ๊ฑฐ๋‚˜ ์ „ ๊ฐ’๊ณผ ๋™์ผํ•œ ๊ฒฝ์šฐ 
            if prev == None or prev == n:
                prev = n
            # ์—ฐ์†๋œ ๊ฒฝ์šฐ 
            elif prev + 1 == n:
                prev = n 
                tempCount += 1 # ์—ฐ์†์ ์ธ ๊ฒฝ์šฐ ์นด์šดํŠธ 
            else:
                prev = n # ์ดˆ๊ธฐํ™” 
                tempCount = 1
                
                
            result = max(result, tempCount) # ๊ฐ’ ๊ฐฑ์‹  
      
        
        return result

 

2์ฐจ ํ’€์ด (ํ•ด์„ค ์ฐธ๊ณ , ์‹œ๊ฐ„๋ณต์žก๋„ O(n))

์•„๋ž˜ ์œ ํˆฌ๋ธŒ๋ฅผ ์ฐธ๊ณ ํ–ˆ๋‹ค. 

https://www.youtube.com/watch?v=P6RZZMu_maU

์•„๋ž˜ ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ๊ฒฝ์šฐ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ณ„์‚ฐํ–ˆ์„๋•Œ, for๋ฌธ ์•ˆ์— while ๋ฌธ์ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— O(n^2) ์•„๋‹Œ๊ฐ€ ์‹ถ๊ธด ํ–ˆ๋Š”๋ฐ, 

์ด๋ฏธ set๋กœ ๋ฐ”๊พธ์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ’์ด ์žˆ๋Š”์ง€ ๊ฒ€์‚ฌํ• ๋•Œ O(1)๋ฐ–์— ๊ฑธ๋ฆฌ์ง€ ์•Š๊ณ , 

์—ฐ์†๋œ ์ˆซ์ž๋ฐฐ์—ด [1,2,3,4]๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ 2,3,4์ผ๋•Œ๋Š” if์กฐ๊ฑด๋ฌธ์— ๋น ์ ธ์„œ ๊ฒ€์‚ฌ๋ฅผ ์•ˆํ•˜๊ณ  1์ผ๋•Œ๋งŒ 1->2->3->4 ๋กœ ๊ฒ€์‚ฌ๋ฅผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ฒฐ๊ณผ์ ์œผ๋กœ O(n)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ๊ฑธ๋ฆฌ๊ฒŒ ๋œ๋‹ค. 

longest = 0
numSets = set(nums)
for n in numSets:
    if n -1 in numSets:
        continue;
    else:
        t = n 
        tlengh = 1 
        while t + 1 in numSets:
            tlengh += 1 
            t = t + 1 

        longest = max(tlengh, longest)

return longest

 

 

๋ฐ˜์‘ํ˜•