less than 1 minute read

136. Single Number

문제 링크

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

문제 설명

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

제한 사항

  • 1 <= nums.length <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4
  • Each element in the array appears twice except for one element which appears only once.

입출력 예 #1

  1. Input : nums = [2,2,1]
  2. Output : 1

입출력 예 #2

  1. Input : nums = [4,1,2,1,2]
  2. Output : 4

입출력 예 #3

  1. Input : nums = [1]
  2. Output : 1

문제 풀이

입력값이 동일하면 False, 다르면 True가 되는 XOR을 활용하여 문제를 풀 수 있다.

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        result = 0
        for num in nums:
            result ^= num

        return result

Comments