#16 3Sum Closest

#16 3Sum Closest

问题描述

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.

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-closest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

与#15 3Sum的思想一样,先排序,在解题。

排序后对列表进行一次遍历,对于每一个元素,都要寻找最接近目标的组合。这里我们使用双指针法,最左和最右各设置一个指针。

时间复杂度:\(O(n\log n)+O(n^2)=O(n^2)\),排序花费\(O(n\log n)\),查找花费\(O(n^2)\)

空间复杂度:\(O(1)\),只需存放最接近目标的值

代码解释

只需注意几个优化点

line 16&22:如对于某个元素\(i\),前三项的和为最小和,后三项的和为最大和,若最小和仍比目标大,或最大和仍比目标小,则只需计算这一种组合。然后继续循环计算元素\(i+1\)

line 20&26:对第一点的补充,若三项之和与目标值相等可直接得到结论

line 28~44:双指针法,start为左指针,end为右指针

line 39&43~42:如果当前指针指向的值与前一项的值相同,那么可以用while循环跳过(当然要注意index超出界限)

Github

posted @ 2020-03-22 18:15  Lyu1997  阅读(120)  评论(0编辑  收藏  举报