1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class Solution: def threeSumClosest(self, nums, target): nums.sort() x = 0 length = len(nums) res = nums[1] + nums[0] + nums[2] if length == 3: return res while x < length: a = nums[x] y = x+1 z = length-1 while y < z: b = nums[y] c = nums[z] Sum = a + b + c if abs(target - Sum) < abs(target - res): res = Sum if Sum > target: z -= 1 elif Sum < target: y += 1 else: res = target return res x += 1 return res
|
近期评论