0000
0000
3月前 · 4 人阅读

给定一个包括n 个整数的数组nums和 一个目标值target。找出nums中的三个整数,使得它们的和与target最接近。返回这三个数的和。假定每组输入只存在唯一答案。

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

import sys
class Solution:
     def threeSumClosest(self, nums, target):
     """ :type nums: List[int] :
            type target: int :
            rtype: int
     """
             result = sys.maxsize
             nums.sort()
             for i in range(len(nums)-2):
                 left =i+1
                 right = len(nums)-1
                 while left <right:
                         temp_sum = nums[i]+nums[left]+nums[right]
                         temp_result = abs(target-temp_sum)
                         if temp_result <result:
                                result_nums=temp_sum
                                 result = temp_result
                        if target > temp_sum:
                                 left+=1
                         elif target < temp_sum:
                                 right-=1
                         else:
                                 break
                    if temp_result==0:
                           break
           return result_nums


收藏 0
nums target result temp sum le
评论 ( 0 )