Zero to Hero
article thumbnail
Published 2021. 4. 7. 11:30
287. Find the Duplicate Number Algorithm
 

Find the Duplicate Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1. 선형 탐색 (시간 초과)

class Solution:
    def findDuplicate(self, nums):
        nums.sort()
        for i in range(1, len(nums)):
            if nums[i] == nums[i-1]:
                return nums[i]

 

2. HashMap or Set (공간 초과)

class Solution:
    def findDuplicate(self, nums):
        seen = set()
        for num in nums:
            if num in seen:
                return num
            seen.add(num)

 

3. Floyd 순환 알고리즘 (2 pointer, Runner)

from typing import *


class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        pointer1 = pointer2 = 0
        while True:
            pointer1 = nums[pointer1]
            pointer2 = nums[pointer2]
            pointer2 = nums[pointer2]
            if pointer1 == pointer2:
                break
        pointer1 = 0
        while pointer1 != pointer2:
            pointer1 = nums[pointer1]
            pointer2 = nums[pointer2]
        return pointer1

'Algorithm' 카테고리의 다른 글

338. Counting Bits  (0) 2021.04.09
310. Minimum Height Trees  (0) 2021.04.08
238. Product of Array Except Self  (0) 2021.04.06
46. Permutations  (0) 2021.04.05
94. Binary Tree Inorder Traversal  (0) 2021.04.05
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!