소프트웨어에 대한 모든 것

LeetCode 풀기 - 136. Single Number 본문

알고리즘/LeetCode

LeetCode 풀기 - 136. Single Number

앤테바 2021. 10. 31. 10:38
반응형

https://leetcode.com/problems/single-number/

 

Single 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

문제)

풀이 전략)

  • XOR 교환법칙 결합법칙 이용
    • A^A = 0
    • A^0=A
    • A^A^B^B^C=0^0^A=A

솔루션1)

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        # 모든 값을 xor 취하면 하나만 남음
        ret = 0
        for num in nums:
            ret ^= num        
        return ret

솔루션2)

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return reduce(lambda x,y : x^y, nums)

 

반응형
Comments