【LeetCode】3Sum Closest 解题报告
来源:互联网 发布:壁虎数据恢复免root版 编辑:程序博客网 时间:2024/05/16 19:51
【题目】
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).【解析】
和 3Sum解题报告 很像,与之不同的是,不再是求三个数的和是不是为0,而是看三个数的和与target的差是否为最小,只需记录当前最优解并不断更新其值就可。
【Java代码】O(n^2)
public class Solution { public int threeSumClosest(int[] num, int target) { if (num == null || num.length < 3) return 0; Arrays.sort(num); int ret = 0; int closestDist = Integer.MAX_VALUE; int len = num.length; for (int i = 0; i < len-2; i++) { if (i > 0 && num[i] == num[i-1]) continue; int l = i+1, r = len-1; while (l < r) { int sum = num[i] + num[l] + num[r]; if (sum < target) { if (target-sum < closestDist) { closestDist = target - sum; ret = sum; } l++; } else if (sum > target) { if (sum-target < closestDist) { closestDist = sum - target; ret = sum; } r--; } else { //when sum == target, return sum. return sum; } } } return ret; }}
容易出错的地方是,把 ret 初始值设为 Integer.MAX_VALUE,然后后面计算 closestDist = Math.abs(ret - target),这样会导致溢出!!
1 0
- 【LeetCode】3Sum Closest 解题报告
- LeetCode 解题报告 3Sum Closest
- LeetCode解题报告--3Sum Closest
- [leetcode] 16. 3Sum Closest 解题报告
- leetcode(16) 3Sum Closest解题报告
- [Leetcode] 16. 3Sum Closest 解题报告
- [LeetCode] 3Sum Closest 解题报告
- leetcode解题报告16. 3Sum Closest
- [LeetCode 解题报告]016. 3Sum Closest
- 3Sum Closest ——解题报告
- [LC解题报告]16. 3Sum Closest
- leetcode解题方案--016--3 sum closest
- [LeetCode]3Sum,解题报告
- 【LeetCode】3Sum 解题报告
- LeetCode解题报告--3 Sum
- [LeetCode] 3Sum 解题报告
- 3Sum LeetCode 解题报告
- 【LeetCode】3Sum,3Sum Closest 题解报告
- 第10周项目1 程序填充与阅读
- 第十周项目0-求最大公约数
- android中shape的使用
- 分别用PopupWindow和AlertDialog实现对话框实例
- 数据结构:线性表之单链表
- 【LeetCode】3Sum Closest 解题报告
- 利用x264lib编码h264流的源码
- HDOJ 题目3466 Proud Merchants(需排序的01背包)
- 1068: 找零钱
- addSubview和insertSubview 区别
- codevs 1482 路线统计
- c++初试-操作符重载(3)
- 黑马程序员——String类的使用
- 汽车人生系列之(二): 关于汽车的几个比喻