Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 백준 9012번
- DFS
- BFS(Breadth First Search)
- 플로이드 워셜 알고리즘(Floyd-Warshall Algorithm)
- 그래프(Graph)
- 이분 그래프(Bipartite Graph)
- 백준 18352번
- 백준 21606번
- 알고리즘 개념
- 이분 탐색(Binary Search)
- 큐(Queue)
- 백준 10000번
- 백준 17608번
- 백준 1948번
- 백준 2493번
- 위상 정렬(Topology Sort)
- DFS(Depth First Search)
- 그리디 알고리즘(Greedy Algorithm)
- 다익스트라 알고리즘(Dijkstra Algorithm)
- 스택(Stack)
- 백준 1707번
- 분할 정복(Divide and Conquer)
- 백준 2261번
- 동적 프로그래밍(Dynamic Programming)
- 백준 2812번
- 트리(Tree)
- 위상 정렬(Topological Sort)
- DFS & BFS
- 백준 2504번
- BFS
Archives
- Today
- Total
Always Be Wise
배열 : 두 수의 합(리트코드 1번) 본문
728x90
▶ 문제 : 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
##### 문제 #####
덧셈하여 타겟을 만들 수 있는 배열의 두 숫자 인덱스를 리턴하라.
##### 입력 #####
nums = [2, 7, 11, 15]
target = 9
##### 출력 #####
[0, 1]
▶ 접근 방법
여러 가지 접근 방법을 생각해볼 수 있었다.
우선, 브루트 포스 방식의 완전탐색을 수행하여 전체 가능한 경우를 모두 살펴볼 수 있었으나
시간 복잡도를 고려할 때, 좋은 방법은 아니었다.
이후, target에서 nums의 숫자를 뺀 결과를 딕셔너리에서 조회하는 방식으로 문제를 해결하였다.
▶ 풀이 코드
from typing import List
nums = [2, 7, 11, 15]
target = 9
def two_sum(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] == target:
return [i, j]
print(two_sum(nums, target))
###################################################
def two_sum(nums: List[int], target: int) -> List[int]:
temp = {}
for index, num in enumerate(nums):
temp[num] = index
print(temp)
for index, num in enumerate(nums):
if target - num in temp and index != temp[target - num]:
return [index, temp[target - num]]
print(two_sum(nums, target))
###################################################
def two_sum(nums: List[int], target: int) -> List[int]:
temp = {}
for index, num in enumerate(nums):
if target - num in temp :
return [temp[target - num], index]
temp[num] = index
print(two_sum(nums, target))
▶ 관련 링크
'알고리즘 > 리트코드' 카테고리의 다른 글
배열 : 세 수의 합(리트코드 15번) (0) | 2022.01.30 |
---|---|
배열 : 빗물 트래핑(리트코드 42번) (0) | 2021.12.15 |
문자열 조작 : 가장 긴 팰린드롬 부분 문자열(리트코드 5번) (0) | 2021.12.14 |
문자열 조작 : 그룹 애너그램(리트코드 49번) (0) | 2021.12.14 |
문자열 조작 : 가장 흔한 단어(리트코드 819번) (0) | 2021.12.14 |
Comments