16. 3Sum Closest

参照: LeetCode15题,三数之和的思路(https://www.jianshu.com/p/dc147505569f)
【Description】
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).

【Idea】

  1. 先排序为有序数组;
  2. 参考3Sum的思想,最外层由Index=0遍历至index=len(nums)-3;
  3. 第二层循环:从边缘递归至中间,跳出条件为left==right。其中需要设置个标记为closest_dis,不断与三数之和到target的距离做判断,然后存储最近的和值到closest_sum;当三数之和等于target时,直接return结果;
  4. 当遍历过程中没有三数之和==target的case,则返回标记的最近和值;
    (以上复杂度为n*n)
image.png

空间复杂度较差, 待优化

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums = sorted(nums)
        closest_dis = abs(nums[0] + nums[1] + nums[-1] - target)
        closest_sum = nums[0] + nums[1] + nums[-1]
        for i in range(len(nums)-2):
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            temp = target-nums[i]
            left = i + 1
            right = len(nums) - 1
            while left < right:
                # print(i, left, right)
                # print(nums[i], nums[left], nums[right])
                if closest_dis > abs(target - nums[left] - nums[right] - nums[i]):
                    closest_dis = abs(target - nums[left] - nums[right] - nums[i])
                    closest_sum = nums[left] + nums[right] + nums[i]
                # print(closest_dis, closest_sum)
                if nums[left] + nums[right] < temp:
                    left += 1
                elif nums[left] + nums[right] > temp:
                    right -= 1
                else:
                    return nums[left] + nums[right] + nums[i]
        return closest_sum

你可能感兴趣的:(16. 3Sum Closest)