leetcode 16-> 3Sum Closest
阿新 • • 發佈:2019-03-12
lee style close exactly col color while ould ==
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.
class Solution(object): def threeSumClosest(self, nums, target): nums.sort() pre_sum= None for i in xrange(len(nums) - 2): head, tail = i+1, len(nums)-1 while head < tail: sum = nums[i] + nums[head] + nums[tail] if pre_sum == None: pre_sum = sum if abs(sum - target) < abs(pre_sum - target): pre_sum= sum if sum < target: head += 1 elif sum > target: tail -= 1 else: return target return pre_sum
leetcode 16-> 3Sum Closest