lc16. 3Sum Closest

142 阅读1分钟
  1. 3Sum Closest Medium

1498

111

Favorite

Share 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).

思路:双指针, 1.首先给nums排序,设置初始res=0 2.for循环nums长度, I.第一次循环,x=0,i=x+1,j=len(nums)-1, II.计算num=nums[x]+nums[i]+nums[j],判断abs(num-target)<abs(res-target),更新res=num III.判断num<target,i++, num>target,j--, num==target,return target 3.下次循环 4.结束之后返回res

代码:python3

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        res = float('inf')#记录num
        nums=sorted(nums)
        print(nums)
        for x in range(len(nums)):
            i=x+1
            j=len(nums)-1
            while(i<j):
                num=nums[x]+nums[i]+nums[j]
                print(num)
                if abs(num-target)<abs(res-target):
                    res=num
                if num==target:
                    return num
                elif num<target:
                    i=i+1
                else:
                    j=j-1
        return res