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 |
Tags
- 리스트의 리스트
- Unique Paths
- Python
- mysql #numa #swap #memory
- 블린이
- 그거봤어?
- 삼성역량테스트
- list of list
- LongestPalindromicSubstring
- 삼성인 아마조니언 되다
- 리트코드
- 트리
- technical debt
- 규칙없음
- 아마조니언
- 프로그래머스
- 기술적 채무
- No Rules Rules
- Envoy
- 나는 아마존에서 미래를 다녔다
- 와썹맨
- 알고리즘
- 파이썬
- Dynamic Programmin
- 김태강
- minimum path sum
- BFS
- leetcode
- 독후감
- 동적 프로그래밍
Archives
- Today
- Total
개발자가 되고 싶은 준개발자
[LeetCode] 16. 3Sum Closest 파이썬 코드 본문
문제
16. 3Sum Closest [Medium]
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example 1: Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). |
Constraints:
- 3 <= nums.length <= 10^3
- -10^3 <= nums[i] <= 10^3
- -10^4 <= target <= 10^4
코드
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
diff = float('inf')
answer = None
for i in range(len(nums)-2):
l, r = i+1, len(nums)-1
while l < r:
three_sum = nums[i] + nums[l] + nums[r]
if three_sum == target:
return target
else:
curr_diff = abs(three_sum - target)
if curr_diff < diff:
diff = curr_diff
answer = three_sum
if three_sum < target:
l += 1
else:
r -= 1
return answer
결과
'알고리즘 공부 > LeetCode' 카테고리의 다른 글
[LeetCode] 7. Reverse Integer 파이썬 코드 (0) | 2021.05.29 |
---|---|
[LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 풀이 및 코드 (0) | 2021.03.07 |
[LeetCode] 230. Kth Smallest Element in a BST 문제 및 풀이 코드 (0) | 2021.03.07 |
[LeetCode] 98. Validate Binary Search Tree 풀이 및 코드 (0) | 2021.02.27 |
[LeetCode] 100. Same Tree 풀이 및 코드 (1) | 2020.09.26 |