leetcode 最接近的三數之和 python
阿新 • • 發佈:2019-01-14
題目連結
給定一個包括 n 個整數的陣列 nums 和 一個目標值 target。找出 nums 中的三個整數,使得它們的和與 target 最接近。返回這三個數的和。假定每組輸入只存在唯一答案。
思路
遍歷三個數字,一個數字順序遍歷,另外兩個採用二分法遍歷
程式碼
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) < 3:
raise Exception('input error')
nums.sort()
threeNums = nums[0] + nums[1] + nums[2]
differ = abs(threeNums - target)
ans = threeNums
for i in range(len(nums) - 2):
low = i + 1
high = len(nums) - 1
while(low < high):
threeNums = nums[i] + nums[low] + nums[high]
if abs(threeNums - target) < differ:
differ = abs(threeNums - target)
ans = threeNums
if threeNums == target:
return target
elif threeNums < target:
while low < high and nums[low + 1] == nums[low]:
low += 1
low += 1
else:
while low < high and nums[high - 1] == nums[high]:
high -= 1
high -= 1
return ans