[LeetCode]Single Number

2023. 5. 1. 13:49·SW개발/코딩테스트

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

 

Single Number - LeetCode

Can you solve this real interview question? 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

leetcode.com

 

문제 분석

주어진 nums 리스트에서 한번만 등장하는 숫자를 찾는 문제입니다.

 

처음 시도한 답안

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        count_dict = {}
        
        for num in nums:
            if num in count_dict:
                count_dict[num] += 1
            else:
                count_dict[num] = 1

        count_dict = sorted(count_dict.items(), key=lambda x: x[1])

        return list(count_dict)[0][0]

접근 방법

  1. nums 배열을 순회하면서 count_dict에 등장한 숫자에 대한 카운트를 누적합니다.
  2. count_dict를 value 기준으로 정렬하면 한번만 등장한 숫자를 구할 수 있습니다.

가장 단순한 방법으로 리스트를 순회해서 등장한 숫자의 카운트를 셉니다. 다만, 배열이 커지면 커질수록 오래 걸린다는 단점이 있습니다.

 

두번째로 시도한 답안 

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        ## RC ##
        ## APPROACH : XOR ##
        
        ## TIME COMPLEXITY : O(N) ##
        ## SPACE COMPLEXITY : O(1) ##
        
        # XOR 연산의 특징 : 같은 값끼리 연산하면 걍 0이 되어버림.
        # 따라서 2개 쌍의 경우 모두 0이 되고 혼자 남은 숫자만 남아버림.
        # 0 XOR 99 = 99

        # If we take XOR of zero and some bit, it will return that bit
        # a XOR 0 = a, a XOR 0=a
        # If we take XOR of two same bits, it will return 0
        # a XOR a = 0 a XOR a=0
        # a XOR b XOR a = (a XOR a) XOR b = 0 XOR b = b 
        # a⊕b⊕a=(a⊕a)⊕b=0⊕b=b
        # So we can XOR all bits together to find the unique number.
        
        a = 0
        for i in nums:
            a ^= i
        return a

접근 방법

  1. XOR 연산을 통해서 한번만 등장하는 숫자를 구할 수 있습니다.

굉장히 놀라운 솔루션을 발견하게 되어서 가져왔습니다. XOR 연산을 이용하는 것입니다.

XOR 연산의 특징은 같은 값끼리 연산하면 결과값이 0이 되어버립니다. 따라서 리스트를 반복하면서 XOR 연산을 한다면, 2개의 쌍이 존재하는 숫자들은 모두 0이 되어버리고 결과적으로 1개만 존재하는 숫자가 남게 됩니다.

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Next Permutation  (0) 2023.05.03
[LeetCode]Linked List Cycle  (0) 2023.05.02
[LeetCode]Best Time to Buy and Sell Stock  (0) 2023.04.30
[LeetCode]Swap Nodes in Pairs  (0) 2023.04.13
[LeetCode]Generate Parentheses  (0) 2023.04.12
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Next Permutation
  • [LeetCode]Linked List Cycle
  • [LeetCode]Best Time to Buy and Sell Stock
  • [LeetCode]Swap Nodes in Pairs
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • SW개발 (303)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (1)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    플레이스토어
    컨트리뷰터
    배달비 공유
    배달
    트리 #AVL #알고리즘 #자료구조
    어플리케이션
    g
    django
    음식
    배공파용
    오픈소스
    라이프 스타일
    Contributor
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Single Number
상단으로

티스토리툴바