[LeetCode] 1. Two Sum

2023. 1. 3. 07:35·BE/algorithm

문제 링크 

https://leetcode.com/problems/two-sum/description/

Intuition

  • 주어진 array의 element 중에 target 값으로 합의 수가 맞는 조합을 찾아야 하면..모든 element를 합해서 확인해 보자
  • first + second index element의 합을 확인하고 넘어가야 한다 

Approach

  • 당장 생각나는건...outer loop에서는 index 0 부터 좌항에 들어가는 인자를 iterate하고 inner loop에서는 우항에 들어가는 인자를 iterate 해서 둘의 합을 확인하는 방법 

Complexity

Time complexity:

  • O(N^2) 

Space complexity:

Code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        
        done = False  
        for ptr1, i in enumerate(nums):
            ptr2 = ptr1 + 1
            while ptr2 < len(nums):
                if (nums[ptr1] + nums[ptr2] == target):
                    done = True 
                    break
                else: 
                    ptr2 += 1
            if (done):
                break

        return [ptr1, ptr2]

그런데 O(N^2) 풀이 보다 더 좋은 방법 없을까? 

저작자표시 비영리 변경금지 (새창열림)

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

[LeetCode] 347. Top K Frequent Elements  (0) 2023.01.04
[LeetCode] 49. Group Anagrams  (0) 2023.01.03
[LeetCode] 242. Valid Anagram  (0) 2022.12.14
[LeetCode] 217. Contains Duplicate  (2) 2022.12.14
[프로그래머스] 다리를 지나는 트럭 - 스택/큐  (0) 2021.07.18
'BE/algorithm' 카테고리의 다른 글
  • [LeetCode] 347. Top K Frequent Elements
  • [LeetCode] 49. Group Anagrams
  • [LeetCode] 242. Valid Anagram
  • [LeetCode] 217. Contains Duplicate
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
  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
bandal-gom
[LeetCode] 1. Two Sum
상단으로

티스토리툴바