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
- leetcode
- 기술적 채무
- BFS
- 삼성역량테스트
- Python
- 리스트의 리스트
- list of list
- 독후감
- mysql #numa #swap #memory
- 나는 아마존에서 미래를 다녔다
- 블린이
- No Rules Rules
- Envoy
- 규칙없음
- 아마조니언
- 알고리즘
- 그거봤어?
- 동적 프로그래밍
- Dynamic Programmin
- 와썹맨
- minimum path sum
- 트리
- technical debt
- Unique Paths
- 파이썬
- LongestPalindromicSubstring
- 리트코드
- 삼성인 아마조니언 되다
- 프로그래머스
- 김태강
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 |