LeetCode 1. Two Sum (Python)

2022. 4. 17. 12:45·알고리즘/리트코드

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

 

Two Sum - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

Solution 1 Brute Force 

  • 시간복잡도 : O(n^2)
  • 공간복잡도 :  O(1)
def twoSum(nums: List[int], target: int) -> List[int]:
    for i in range(len(nums)):
    	for j in range(i+1, len(nums)):
        	if (nums[i] + nums[j]) is target:
            	return [i, j]

    return [-1, -1]

Solution 2 Hash Table 

  • 시간복잡도 : O(n)
  • 공간복잡도 :  O(n)
def twoSum(nums: List[int], target: int) -> List[int]:
    hashtable_dict = {}

    for i in range(len(nums)):
        value = target - nums[i]

        # get으로 찾으면 None을 돌려주고, []로 찾으면 Key오류 발생 시킴
        if hashtable_dict.get(value) is not None and hashtable_dict[value] != i:
            return sorted([i, hashtable_dict[value]])

        hashtable_dict[nums[i]] = i

    return [-1, -1]

'알고리즘 > 리트코드' 카테고리의 다른 글

LeetCode 88. Merge Sorted Array (Python)  (0) 2022.04.17
LeetCode 35.Search Insert Position (Python)  (0) 2022.04.17
LeetCode 26. Remove Duplicates From Sorted Array (Python)  (0) 2022.04.17
LeetCode 66 Plus One  (0) 2022.04.10
'알고리즘/리트코드' 카테고리의 다른 글
  • LeetCode 88. Merge Sorted Array (Python)
  • LeetCode 35.Search Insert Position (Python)
  • LeetCode 26. Remove Duplicates From Sorted Array (Python)
  • LeetCode 66 Plus One
고구마와 감자
고구마와 감자
Amor DevFati는 김연자-Amor Fati에 Development(개발)의 Dev 를 첨가하여 만든 이름
  • 고구마와 감자
    Amor DevFati(아모르 개발파티)
    고구마와 감자
  • 전체
    오늘
    어제
    • 분류 전체보기 (156)
      • Loopers 2기 (4)
      • 스프링 (5)
      • 알고리즘 (113)
        • 백준 (70)
        • 프로그래머스 (7)
        • 인프런_자바코테강의 (20)
        • 리트코드 (5)
        • 해커랭크 (0)
        • 코드업 (3)
        • 이것저것 (7)
      • 자바 (7)
      • GIT (0)
      • 파이썬 (1)
      • 개발이론 (4)
      • JPA (0)
      • 김영한 강의 (13)
        • 모든 개발자를 위한 HTTP 웹 기본 지식 (2)
        • 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 (6)
        • 스프링 핵심 원리 - 기본편 (5)
      • 일기 및 아무말 적기 (6)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    남욱이의 닭장
    11966
    1247
    조교는 새디스트야!!
    첫 글자를 대문자로
    3059
    5361
    1598
    고려대학교에는 공식 와인이 있다
    2921
    백준
    등장하지 않는 문자의 합
    Mini Fantasy War
    그대로출력하기2
    꼬리를 무는 숫자 나열
    전투 드로이드 가격
    홀수일까 짝수일까
    더하기 3
    할로윈의 사탕
    14656
    2의 제곱인가
    5988
    10409
    4458
    16673
    2857
    카이사르 암호
    11023
    스프링 핵심 원리
    10178
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
고구마와 감자
LeetCode 1. Two Sum (Python)
상단으로

티스토리툴바