[LeetCode] 217. Contains Duplicate

2022. 12. 14. 13:31·BE/algorithm

Intuition

  • python 으로 문제 풀이를 하기로 했으니 counter 함수를 사용해서 풀이하면 될것같다!

Approach

  • counter 함수로 첫번째 풀이를 했는데, time limit exceeded 가 떴음
  • 두번째 제출에서는 set 자료구조를 사용해서 풀이
    • set은 중복을 허용 X
    • 주어진 data set을 set에 넣으면 중복이 사라져서 전체 사이즈가 달라짐
    • set의 사이즈와 nums의 사이즈를 비교!

Complexity

Time complexity:

  • first attempt:
    • O(N^2)
    • list.count() 함수는 내부적으로 모든 PyObject를 iterate 하고, 주어진 입력값과 compare 하기 때문에 O(N) complexity를 가진다
      • 참고: https://stackoverflow.com/questions/44812468/what-is-the-time-complexity-of-python-lists-count-function
  • second attempt:

Space complexity:

  • first attempt:
  • second attempt:

Code

first attempt

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        for num in nums: 
            if (nums.count(num) >= 2): 
                return True 
            else: 
                continue

        return False

second

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:

        return len(nums) != len(set(nums))
저작자표시 비영리 변경금지 (새창열림)

'BE > algorithm' 카테고리의 다른 글

[LeetCode] 1. Two Sum  (0) 2023.01.03
[LeetCode] 242. Valid Anagram  (0) 2022.12.14
[프로그래머스] 다리를 지나는 트럭 - 스택/큐  (0) 2021.07.18
[프로그래머스] K번째수 - 정렬  (0) 2021.07.18
[프로그래머스] 완주하지 못한 선수 - 해시  (0) 2021.07.18
'BE/algorithm' 카테고리의 다른 글
  • [LeetCode] 1. Two Sum
  • [LeetCode] 242. Valid Anagram
  • [프로그래머스] 다리를 지나는 트럭 - 스택/큐
  • [프로그래머스] K번째수 - 정렬
bandal-gom
bandal-gom
Devops & Backend Developer | tech blog
  • bandal-gom
    yayz's devlog
    bandal-gom
  • 전체
    오늘
    어제
    • 분류 전체보기 (68)
      • DevOps (22)
        • devops (4)
        • cicd (2)
        • docker (2)
        • monitoring (2)
        • nginx (4)
        • cache (1)
        • aws (1)
        • etc (6)
      • BE (21)
        • BE (3)
        • design pattern (1)
        • data structure (0)
        • spring (1)
        • algorithm (12)
      • devlog (24)
        • TIL (17)
        • programming language (2)
        • conference (2)
        • etc (3)
      • IT Review (1)
  • 블로그 메뉴

    • about.
    • 개발👩‍💻
    • etc.
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    알고리즘문제풀이
    leetcode 347
    Kotlin
    java
    오블완
    til
    jenkins
    hash
    노트북하기좋은카페
    Programmers
    티스토리챌린지
    99클럽
    문제풀이
    항해99
    코딩테스트준비
    릿코드
    알고리즘
    모각코
    젠킨스
    algorithm
    개발자취업
    NGINX
    LeetCode
    Python
    homelab
    키보드케이블
    프로그래머스
    키캡
    time complexity
    array
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
bandal-gom
[LeetCode] 217. Contains Duplicate
상단으로

티스토리툴바