알고리즘 공부/LeetCode
[LeetCode] 16. 3Sum Closest 파이썬 코드
준개발자
2021. 5. 29. 16:36
문제
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