[NeetCode/Python] Two Integer Sum

2024. 8. 31. 03:07·Algorithm/NeetCode

문제 링크:

https://neetcode.io/problems/two-integer-sum

 

NeetCode

 

neetcode.io

 

합이 타겟이 되는 두 수를 찾는 문제다. 반드시 한 쌍의 숫자만 타겟 숫자를 만들 수 있다.

 

 

[나의 풀이]

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums) - 1):
            pair = target - nums[i]
            for j in range(i + 1, len(nums)):
                if nums[j] == pair:
                    return [i, j]

        return []

간단하게 이중 for문으로 합을 구하도록 했다.

 

[솔루션 풀이]

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        prevMap = {}  # val -> index

        for i, n in enumerate(nums):
            diff = target - n
            if diff in prevMap:
                return [prevMap[diff], i]
            prevMap[n] = i

 

 

내 풀이와의 차이점은 그거다

나는 이중 for문으로 현재 숫자와 그 이후의 숫자의 합을 찾으려 했다면,

솔루션은 현재 숫자와 그 이전의 숫자의 합을 찾으려 한 것이다. 그래서 이전 숫자들을 prevMap에 따로 index와 매핑해두었다.

사실 시간 복잡도는 비슷하지만(in의 시간 복잡도도 O(n)), 뭔가 코드 적으로 훨씬 깔끔해 보인다.

 

이런 흐름의 전환은 다시금 익혀야할 부분이다!

 

시간 복잡도

최악의 경우 O(n^2)

참고: https://wiki.python.org/moin/TimeComplexity

'Algorithm > NeetCode' 카테고리의 다른 글

[NeetCode/Python] Min Cost Climbing Stairs  (0) 2024.09.19
[NeetCode/Python] Kth Largest Integer in a Stream  (0) 2024.09.03
[NeetCode/Python] Plus One  (0) 2024.08.30
[NeetCode/Python] Climbing Stairs  (0) 2024.08.17
[NeetCode/Python] Find Target in Rotated Sorted Array  (0) 2024.08.08
'Algorithm/NeetCode' 카테고리의 다른 글
  • [NeetCode/Python] Min Cost Climbing Stairs
  • [NeetCode/Python] Kth Largest Integer in a Stream
  • [NeetCode/Python] Plus One
  • [NeetCode/Python] Climbing Stairs
빵빵0
빵빵0
(아직은) 공부하고 정리하는 블로그입니다.
  • 빵빵0
    Hack Your World
    빵빵0
  • 전체
    오늘
    어제
    • 분류 전체보기 (87)
      • Error Handling (7)
      • Project (5)
        • MEV (2)
      • Architecture (0)
        • API (0)
        • Cache (0)
        • 사소한 고민거리 (0)
      • Computer Science (4)
        • Data Structure (2)
        • Database (1)
        • Cloud (0)
        • OS (0)
        • Infra, Network (1)
        • AI (0)
      • Language (7)
        • Go (7)
        • Rust (0)
        • Python (0)
        • Java (0)
      • Algorithm (40)
        • BaekJoon (18)
        • Programmers (7)
        • LeetCode (6)
        • NeetCode (9)
      • SW Books (9)
        • gRPC Up & Running (1)
        • System Design Interview (2)
        • 스프링 입문을 위한 자바 객체지향의 원리와 이해 (6)
        • 블록체인 해설서 (0)
        • 후니의 쉽게 쓴 CISCO 네트워킹 (0)
      • BlockChain (4)
        • Issues (0)
        • Research (4)
        • Tech (0)
      • Own (5)
        • TIR(Today I Read) (0)
        • Personal (2)
        • Novel (0)
        • Memo (3)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    goroutine
    go
    BEAKJOON
    Python
    LeetCode
    context
    KBW
    DP
    블록체인
    Programmers
    2024
    two pointer
    BaekJoon
    MEV
    chart
    ethereum
    Greedy
    candlechart
    blockchain
    golang
    스택
    EVM
    BFS
    큐
    NeetCode
    Hash Table
    프로그래머스
    Palindrome
    MongoDB
    백준
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
빵빵0
[NeetCode/Python] Two Integer Sum
상단으로

티스토리툴바