LeetCode Everyday:堅持價值投資,做時間的朋友!!!
題目:
給定一個包括 n 個整數的數組nums
和 一個目標值target
。找出nums
中的三個整數,使得它們的和與target
最接近。
返回這三個數的和。假定每組輸入只存在唯一答案。
示例:
-
示例 1:
輸入:nums = [-1,2,1,-4], target = 1 輸出:2 解釋:與 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
-
提示:
- 3 <= nums.length <= 10^3
- -10^3 <= nums[i] <= 10^3
- -10^4 <= target <= 10^4
代碼
方法一: 排序 + 雙指針
執行用時:132 ms, 在所有 Python3 提交中擊敗了55.43%的用戶
內存消耗:13.6 MB, 在所有 Python3 提交中擊敗了9.38%的用戶
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
n=len(nums)
if(not nums or n<3):
return None
nums.sort()
res=float("inf")
for i in range(n):
if(i>0 and nums[i]==nums[i-1]):
continue
L=i+1
R=n-1
while(L<R):
cur_sum=nums[i]+nums[L]+nums[R]
if(cur_sum==target):
return target
if(abs(cur_sum-target)<abs(res-target)):
res=cur_sum
if(cur_sum-target<0):
L+=1
else:
R-=1
return res
"""
For Example: input: nums = [-1,2,1,-4], target = 1
output: 2
"""
nums = [-1,2,1,-4]
target = 1
solution = Solution()
result = solution.threeSumClosest(nums, target)
print('輸出爲:', result) # 2
參考
- https://leetcode-cn.com/problems/3sum-closest/solution/pai-xu-shuang-zhi-zhen-jian-dan-qing-xi-python3-by/