saurus2
Saurus2
saurus2
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발
      • AJAX
    • ML Ops
    • Profile
    • 음식점
    • 배낭여행
    • 컴퓨터공학
      • 알고리즘 공부
      • C++
      • Sever 스터디
      • Java spring
      • 알고리즘 _ 문제해결
      • 딥러닝
      • Java 정리
      • Python
      • LeetCode 1000
      • Machine Learning Study
      • Sign language Detection Pro..
      • LeetCode Solutions
    • 비콘
    • 데일리 리포트
    • 유학일기
      • 영어 공부
      • Daily
    • AI Master Degree
      • Data Mining
      • AI and Data engineering
      • Math Foundations for Decisi..
      • Natural Language Processing

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 알고리즘문제해결
  • 개발자
  • 취업준비
  • 온라인저지
  • 리트코드
  • two pointer
  • Python
  • 알고리즘
  • 딥러닝
  • c++
  • BFS
  • DFS
  • 개발자 취업준비
  • 딕셔너리
  • 릿코드
  • LeetCode
  • 파이썬
  • 백준
  • 문제해결능력
  • 취준

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
saurus2

Saurus2

카테고리 없음

[LeetCode] 136. Single Number

2022. 8. 14. 08:58

136. Single Number

Easy

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.

문제 해설

문제 접근

  1. 숫자들이 들어있는 리스트의 크기는 N^2 시간복잡도 알고리즘을 사용해도 문제없어 보인다. 
  2. 숫자의 값 크기도 신경쓰지 않아도 될 것 같다. 
  3. 각 숫자는 한번 나타는 숫자 이외에는 두번씩 나온다. 

풀이

  1. Set 을 사용하여 숫자를 집어 넣는다.
  2. 만일 숫자가 존재하면 제거한다.
  3. 마지막에 남은 숫자를 pop 하여 리턴한다.

소스 코드

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        hashset = set()
        for num in nums:
            if num in hashset:
                hashset.remove(num)
            else:
                hashset.add(num)
        return hashset.pop()

 

저작자표시 (새창열림)
    saurus2
    saurus2
    Simple is Best

    티스토리툴바