[LeetCode]Two Sum

2023. 3. 18. 18:55·SW개발/코딩테스트

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

 

Two Sum - LeetCode

Can you solve this real interview question? Two Sum - Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not

leetcode.com

 

문제 분석

주어진 nums 값에서 두 숫자를 골라 더해 target 값을 만드는 문제입니다.

항상 1개의 answer만이 도출됨이 보장되어 있습니다.

 

처음 시도한 답안 O(n^2)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for idx, num in enumerate(nums):
            second_num = target - num
            if second_num in nums:
                second_num_idx = nums.index(second_num)
                if idx != second_num_idx:
                    return [idx, second_num_idx]

접근 방법

  1. nums를 순회하면서 target 에서 뺀 값을 구합니다.
  2. second_num 값이 nums에 있다면 그 시점의 idx와 second idx를 구합니다.
  3. 단, 이 때 같은 인덱스가 되지 않도록 조건을 걸어둡니다.

처음 시도한 답안의 시간 복잡도는 O(n^2) 입니다. n번 반복을 통해 순회하고 * second_num이 nums 리스트 안에 있는지 구하기 때문입니다. 우선은 정답을 맞출 수 있었으나, 문제에서 O(n^2) 아래로도 낮출 수 있다는 점이 언급되어 있어서 다른 해결책을 찾아 보았습니다.

(ps. `element in 리스트` 의 시간 복잡도는 O(n) 입니다.)

 

두번째로 시도한 답안 O(n)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        """
        O(n) hasp map.
        """
        hashmap = {}
        for index, value in enumerate(nums):
            if target - value in hashmap:
                return [hashmap[target - value], index]
            hashmap[value] = index

접근 방법

  1. nums를 순회합니다.
  2. hasp map 안에 target - value 값이 있는지 확인합니다.
  3. 있다면 hasp map안의 인덱스와, 현재의 index를 return 합니다.
  4. 없다면 hasp map에 저장합니다.

두번째 방법은 hasp map을 활용하는 방법입니다. 반복문을 순회 하다보면 종료 직전의 hash map은 다음과 같이 저장되어 있습니다.

Input: nums = [3, 2, 4], target = 6

hasp_map 
{3: 0, 2: 1}

즉, 첫번째에 해당하는 num이 key, idx가 value로서 저장되어 있습니다. 그렇게 순회하다 target - value인 값이 hasp_map 안에 있다면 종료됩니다.

(ps. `element in 딕셔너리` 의 시간 복잡도는 O(1) 입니다.)

 

728x90

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

[LeetCode]Longest Common Prefix  (0) 2023.03.19
[LeetCode]Roman to Integer  (0) 2023.03.18
[프로그래머스]정수 삼각형 - DP  (0) 2021.12.31
[프로그래머스]N으로 표현 - DP  (0) 2021.12.31
[프로그래머스]여행경로 - DFS/BFS  (0) 2021.12.13
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Longest Common Prefix
  • [LeetCode]Roman to Integer
  • [프로그래머스]정수 삼각형 - DP
  • [프로그래머스]N으로 표현 - DP
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (309)
      • SW개발 (305)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (3)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

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

티스토리툴바