3Sum Closest解題報告
阿新 • • 發佈:2018-12-05
題目
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:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解法一:暴力解
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ result = nums[0] + nums[1] + nums[2] min = abs(result-target) for i in range(len(nums)-2): for j in range(i+1,len(nums)-1): for k in range(j+1,len(nums)): if abs(nums[i]+nums[j]+nums[k]-target) < min: result = nums[i]+nums[j]+nums[k] min = abs(nums[i]+nums[j]+nums[k]-target) return result
思路太簡單就不說了,然後就被time limit打了臉,做題果然是要多想想才行。
解法二:端點法
參考了一下大佬的做法,果然還是端點大法好。。。上次掉了一次坑,這次又掉了進去。
class Solution(object): def threeSumClosest(self, nums, target): result = nums[0] + nums[1] + nums[2] min = abs(result-target) nums.sort() # 分i = 0和i > 0 的情況分別進行討論 for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i-1]: continue # 一模一樣的情況就不需要分析了 # 端點運動開始 start = i + 1 end = len(nums) - 1 while start < end: value = nums[i] + nums[start] + nums[end] if abs(value - target) < min: result = value min = abs(value - target) if value == target: return result elif value > target: end = end - 1 else: start = start + 1 return result