[Leetcode]128. Longest Consecutive Sequence

2024. 7. 31. 22:08Algorithm

1. problem :

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

 

2. solution 1 :

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:   
        if len(nums) == 0 or len(nums) == 1:
            return len(nums)    
        nums = sorted(nums)
        max_count = 1 
        count = 1
        for i in range(1,len(nums)):
            if nums[i] == nums[i-1]:
                continue 
            elif nums[i] == nums[i-1] + 1:
                count += 1 
            else:
                max_count = max(count,max_count)
                count = 1 
        max_count = max(max_count,count)
        return max_count

한줄평 : 같으면 continue,  +1 크면 count +=1 , 다르다면 거기서 스탑. max_count 갱신 후, count = 1로 다시 설정.