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解决就可以了),那我们就必须进行相应的更新喽。
代码:
下面就是指针移动和题目所求的三个数之和如何更新:
- leetcode之3Sum Closest 问题
- leetcode之3Sum Closest
- LeetCode之3Sum Closest
- 【Leetcode】之3Sum Closest
- leetcode之3Sum Closest
- leetcode之 3Sum Closest
- leetcode 题解 || 3Sum Closest 问题
- LeetCode进阶之路(3Sum Closest)
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- 使用正则表达式从一段字符串中匹配出img标签的src值
- 洛谷 P1125 笨小猴
- 数组
- 数组知识点
- Python3 urllib模块使用
- leetcode之3Sum Closest 问题
- 洛谷 P1149 火柴棒等式
- 2017年年中反思
- 洛谷 P1351 联合权值
- MongoDB 安装和可视化工具
- Java中的设计模式
- 7.5 Hibernate:内置生成器 – identity
- Java用HttpsURLConnection访问https网站的时候如何跳过SSL证书的验证?
- Random取100以内的随机数