美文网首页
16. 3Sum Closest

16. 3Sum Closest

作者: Chiduru | 来源:发表于2019-03-12 17:06 被阅读0次

参照: 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

相关文章

  • LeetCode #16 2018-07-28

    16. 3Sum Closest Given an array nums of n integers and an...

  • Day3

    16. 3Sum Closest Given an array S of n integers, find thr...

  • LeetCode 16. 3Sum Closest

    16. 3Sum Closest Given an array S of n integers, find thr...

  • 16. 3Sum Closest

    题目: Given an array S of n integers, find three integers i...

  • 16. 3Sum Closest

    题目: 给定一个nums由n个整数和一个整数组成的数组target,找出三个整数nums,使总和最接近target...

  • 16. 3Sum Closest

    Given an array nums of n integers and an integer target, ...

  • 16. 3Sum Closest

    Description Given an array S of n integers, find three in...

  • 16. 3Sum Closest

    Given an array nums of n integers and an integer target, ...

  • 16. 3Sum Closest

    Description Given an array S of n integers, find three in...

  • 16. 3Sum Closest

    先排序,然后左右夹逼,每次当sum-target < diff 用diff记录下最小距离

网友评论

      本文标题:16. 3Sum Closest

      本文链接:https://www.haomeiwen.com/subject/pgmnpqtx.html