LeetCode/공통

[LeetCode 75] Easy - 136. Single Number

hyunkookim 2024. 11. 9. 15:22

136. Single Number

 

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.

 

Example 1:

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

Example 2:

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

Example 3:

Input: nums = [1]
Output: 1

 

Constraints:

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

문제 설명

주어진 **정수 배열 nums**에서 모든 원소는 두 번씩 등장하지만, 오직 한 원소만 한 번 등장합니다. 이 한 번만 등장하는 원소를 찾아야 하는 문제입니다.


문제 조건

  1. 입력 조건:
    • 배열 nums의 길이는 1 ≤ nums.length ≤ 3 × 10^4.
    • 배열의 각 원소는 −3 × 10^4 ≤ nums[i] ≤ 3×10^4.
    • 모든 원소는 두 번씩 등장하지만, 단 하나의 원소만 한 번 등장합니다.
  2. 출력 조건:
    • 한 번만 등장하는 원소를 반환합니다.
  3. 제약 사항:
    • 선형 시간 복잡도 O(n)로 해결해야 합니다.
    • 추가 공간 복잡도는 상수 O(1) 여야 합니다.

 

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        # 결과 변수 초기화
        res = 0
        
        # 모든 원소를 XOR
        for num in nums:
            res ^= num
        
        # XOR 연산 결과 반환
        return res

 

https://youtu.be/qMPX1AOa83k?si=wYt3_aNAAw3ZSsJR

 

2번째, 3번째 시도:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        stack = []

        for n in nums:
            if n not in stack:
                stack.append(n)
            else:
                stack.remove(n)

        return stack[0]

 

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
    	"""
        # XOR 은 
        # 동일한 값을 XOR 하면, 0이고
        # 0과 어떤 값을 원래 값 그대로 나옴
        # python 에서 XOR 연산은 ^ 임
        """

        res = nums[0]
        for i in range(1, len(nums)):
            res ^= nums[i]
        return res