| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- 헤드라인
- 백준2225
- 20201011뉴스
- 20201018뉴스
- 20201017뉴스
- 오늘의뉴스
- 헤드라인모음
- 코테
- 20201015뉴스
- LeetCode #Python #알고리즘 #코딩테스트 #interview
- 백준
- 크롤링
- 뉴스헤드라인
- 알고리즘
- 20201016뉴스
- 기사헤드라인
- MySQL
- Python
- 20201013뉴스
- 헤드라인기사
- 파이썬
- 경제뉴스
- 뉴스
- 헤드라인뉴스
- json
- 기사
- 20200816뉴스
- encoding
- C++
- 20200615뉴스
Archives
- Today
- Total
HelloCho
[Python] #16. 3Sum Closest(Medium) 본문
문제 :

15번 문제는... 아래 링크의 15번 문제와 유사하다 (사실 하루에 다 풀어본건 함정..)
이 문제는 target과 차이가 최소인 조합을 찾는 문제이다.
[Python] 15. 3Sum(Medium)
문제 : 이 문제는 nums 배열에서 3개의 값을 더해 0을 만들 수 있는 조합을 찾는 문제이다. 역시나.. 프로그래밍 초보인 나는 처음 이 문제를 보고... 아 for문을 3개 써서 중복이 아닌 것의 조합을 넣
hellocho.tistory.com
해결 방법은 위의 링크와 매우 유사하다.
두 개의 포인터를 이용해서 모든 값을 순회한다.
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
diff = float('inf')
nums.sort()
for idx,a in enumerate(nums):
l,r = idx +1, len(nums)-1
while l < r :
three_sum = a + nums[l] + nums[r]
if abs(target - three_sum) < abs(diff):
diff = target - three_sum
if three_sum > target:
r -= 1
else:
l += 1
if diff == 0 :
break
return target- diff
l과 r 두개의 포인터를 설정하고 3개의 값을 더한다. target과 three_sum의 차이가 기존의 diff보다 작다면 diff를 바꾼다.
결과는 아래와 같다.

128ms (O(n^2), 14MB로 통과!
'코테 > LeetCode' 카테고리의 다른 글
| [Python] #36. Valid Sudoku(Medium) (0) | 2020.09.17 |
|---|---|
| [Python] #18. 4Sum(Medium) (0) | 2020.09.15 |
| [Python] 15. 3Sum(Medium) (0) | 2020.09.15 |
| [Python] #59. Spiral Matrix II(Medium) (0) | 2020.09.11 |
| [Python] #54. Spiral Matrix(Medium) (0) | 2020.09.11 |
Comments