sy1214ei 님의 블로그

[Leet Code] 645. Set Mismatch - Python 본문

[Coding]

[Leet Code] 645. Set Mismatch - Python

sy1214ei 2024. 11. 28. 21:31

https://leetcode.com/problems/set-mismatch/description/

Level : Easy
Topic : Array | Hash Table | Bit Manipulation | Sorting

 

class Solution:
    def findErrorNums(self, nums: List[int]) -> List[int]:
        # 1~n 까지의 합 : (n(n+1))/2
        # nums = [1,2,2,4]
        # n = len(nums)
        # orgin_sum = (n(n+1))/2         : [1,2,3,4]의 합
        # duplicate = nums_sum - set_sum : [1,2,2,4] - [1,2,  4] = 2
        # missing = orgin_sum - set_sum  : [1,2,3,4] - [1,2,  4] = 3
        n = len(nums)
        orgin_sum = (n*(n+1)) // 2 # 1~n 까지 합의 공식
        duplicate = sum(nums) - sum(set(nums))
        missing = orgin_sum - sum(set(nums))
        return [duplicate, missing]

        # Time Complexity : O(1)
        # Space Complexity : O(1)