Published:
Updated:

  • Reference
  • 첫번째 μ ‘κ·Όν–ˆλ˜ 방식은 μ“°λ ˆκΈ°λΌκ³  써놓은 만큼 논리적 였λ₯˜κ°€ μ—„μ²­λ‚œ λ°©μ‹μ΄μ—ˆλ‹€.
  • λ‘λ²ˆμ§Έ 방식은 λ°˜λ³΅λ¬Έμ„ λŒλ©΄μ„œ i-1λ²ˆμ§Έμ™€ iλ²ˆμ§Έμ— 따라 cntλ₯Ό μ¦κ°€ν•˜κ³  말고 λ“±λ“± μ—„μ²­ λ³΅μž‘ν•˜κ²Œ μƒκ°ν•˜λ©΄μ„œ ν’€μ–΄λ΄€λŠ”λ° λ„μ €νžˆ ν’€λ¦¬μ§ˆ μ•Šμ•˜λ‹€.
  • λ¦Ώμ½”λ“œ λ„μ›€μœΌλ‘œ xor (λΉ„νŠΈ μ—°μ‚°μž)둜 2κ°œκ°€ λ™μΌν•˜λ©΄ 계산이 λ˜κ²Œλ”ν•˜λŠ” 아이디어λ₯Ό μ•Œ 수 μžˆμ—ˆλ‹€.
  • Runtime 137 ms
  • Beats 66.26%
  • μ‹œκ°„λ³΅μž‘λ„: O(N)


SolutionPermalink

from typing import List


class Solution:
    # λΉ„μ–΄ μžˆμ§€ μ•Šμ€ μ •μˆ˜ 배열이 μ£Όμ–΄μ‘Œμ„ λ•Œ, ν•œ 개λ₯Ό μ œμ™Έν•œ λͺ¨λ“  μš”μ†Œκ°€ 두 번 λ‚˜νƒ€λ‚¨
    # κ·Έ μ œμ™Έλœ ν•œ 개의 μš”μ†Œκ°€ 무엇인지 찾자!
    # linear runtime complexity: O(N) μ‹œκ°„ λ³΅μž‘λ„
    def singleNumber(self, nums: List[int]) -> int:
        # μ“°λ ˆκΈ°
        # nums.sort()
        # # μ •λ ¬ν•˜λ©΄ 닡은 nums[len(nums) - 1] or nums[0]
        # if len(nums) > 1:
        #     if nums[0] == nums[1]:
        #         return nums[len(nums) - 1]
        #     if nums[len(nums) - 1] == nums[len(nums) - 2]:
        #         return nums[0]
        # else:  # Example 3κ³Ό 같은 상황
        #     return nums[0]

        # i-1κ³Ό iλ₯Ό 계속 λŒλ©΄μ„œ cntλ₯Ό μ¦κ°€μ‹œμΌœλ³ΌκΉŒ..? -> X
        # μœ„μ²˜λŸΌ μ“°μ§€ 말고 XOR λΉ„νŠΈ μ—°μ‚°μž μ‚¬μš©ν•˜μž
        # 2κ°œκ°€ 같을 λ•Œ μ²΄ν¬λ˜λŠ” μ•„μ΄λ””μ–΄λ‘œ!
        answer = 0
        for i in nums:
            answer ^= i

        return answer

print(Solution().singleNumber([2, 2, 1]))
print(Solution().singleNumber([4, 1, 2, 1, 2]))
print(Solution().singleNumber([1]))

# Expected: 354
print(Solution().singleNumber(
    [-336, 513, -560, -481, -174, 101, -997, 40, -527, -784, -283, -336, 513, -560, -481, -174, 101, -997, 40, -527,
     -784, -283, 354]))

Leave a comment