leetcode之3Sum Closest 问题

来源:互联网 发布:淘宝同款 编辑:程序博客网 时间:2024/06/13 06:42

题目:

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

示例:

For example, given array S = {-1 2 1 -4}, and target = 1.

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

问题来源:3SumCloset(地址:https://leetcode.com/problems/3sum-closest/#/description)

思路:这道题思路和2Sum,3Sum,4Sum...kSum等几乎没啥区别,可以说几乎是一模一样,只是把等于target(可以理解为绝对值为0)改成了最靠近target(理解为绝对值最小),其它的重复性判断啥的没啥不一样的吧。

          还是简单说一下指针移动

            1)当前三个元素之和比target要小,则我们将最左边的指针往右移(因为数组已经排序了,小的往右移才有可能等于或者缩小和目标target之间的差距);

            2)同理,当前三个元素之和比target要大,则我们将最右边的指针往左移;

            3)等于不就直接大功告成了吗,直接返回即可

注意事项(更新过程):在遍历的过程当中,如果当前三个数之和比原来三个数之和更加靠近target(靠近只需要采用绝对值函数abs解决就可以了),那我们就必须进行相应的更新喽。

代码:

下面就是指针移动和题目所求的三个数之和如何更新:




原创粉丝点击