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
- 백준 2504번
- 백준 17608번
- 동적 프로그래밍(Dynamic Programming)
- 다익스트라 알고리즘(Dijkstra Algorithm)
- 백준 21606번
- 그리디 알고리즘(Greedy Algorithm)
- 그래프(Graph)
- 알고리즘 개념
- 스택(Stack)
- 백준 2493번
- 백준 1707번
- DFS
- 위상 정렬(Topology Sort)
- 백준 2812번
- 백준 2261번
- 백준 1948번
- 백준 10000번
- 이분 탐색(Binary Search)
- DFS(Depth First Search)
- BFS(Breadth First Search)
- 이분 그래프(Bipartite Graph)
- BFS
- 위상 정렬(Topological Sort)
- 트리(Tree)
- 분할 정복(Divide and Conquer)
- 백준 9012번
- DFS & BFS
- 백준 18352번
- 플로이드 워셜 알고리즘(Floyd-Warshall Algorithm)
- 큐(Queue)
Archives
- Today
- Total
Always Be Wise
배열 : 세 수의 합(리트코드 15번) 본문
728x90
▶ 문제 : https://leetcode.com/problems/3sum/
3Sum - 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
##### 문제 #####
# 배열을 입력받아 합으로 0을 만들 수 있는 3개의 엘리먼트를 출력하라.
##### 입력 #####
# nums = [-1, 0, 1, 2, -1, -4]
##### 출력 #####
# [[-1,-1,2],[-1,0,1]]
▶ 접근 방법
1) 브루트 포스로 계산
입력 받은 리스트를 우선 정렬하고, 리스트의 요소를 i, j, k로 하여
세 개의 포인터를 이동시키면서 i + j + k = 0이 되는 값을 찾아낸다.
그런데 중복되는 값이 있을 수 있으므로 해당 경우는 넘어갈 수 있도록 구현한다.
2) 순열로 계산
원소가 3개인 순열 리스트를 만들어서, 해당 리스트의 합이 0을 찾는다.
3) 투 포인터를 이용하여 계산
i를 고정시키고 j, k 값을 투 포인터로 하여 값을 계산한다.
▶ 풀이 코드
nums = [-1, 0, 1, 2, -1, -4]
def three_sum(nums: list) -> list:
result = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, len(nums) - 1):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
for k in range(j + 1, len(nums)):
if k > j + 1 and nums[k] == nums[k - 1]:
continue
if nums[i] + nums[j] + nums[k] == 0 :
result.append([nums[i], nums[j], nums[k]])
return result
print(three_sum(nums))
# [[-1, -1, 2], [-1, 0, 1]]
def three_sum2(nums: list) -> list:
nums.sort()
temp = list(combinations(nums, 3))
result = []
for i in temp :
if sum(i) == 0 and list(i) not in result:
result.append(list(i))
return result
print(three_sum2(nums))
def three_sum3(nums: list) -> list:
result = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, len(nums) - 1
while left < right:
sum = nums[i] + nums[left] + nums[right]
if sum < 0:
left += 1
elif sum > 0:
right -= 1
else :
result.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
return result
print(three_sum3(nums))
▶ 관련 링크
'알고리즘 > 리트코드' 카테고리의 다른 글
스택 : 유효한 괄호(리트코드 20번) (0) | 2022.02.02 |
---|---|
배열 : 주식을 사고 팔기 가장 좋은 시점(리트코드 121번) (0) | 2022.01.31 |
배열 : 빗물 트래핑(리트코드 42번) (0) | 2021.12.15 |
배열 : 두 수의 합(리트코드 1번) (0) | 2021.12.15 |
문자열 조작 : 가장 긴 팰린드롬 부분 문자열(리트코드 5번) (0) | 2021.12.14 |
Comments