*Leetcode - 3Sum Closest
来源:互联网 发布:mysql的级联删除 编辑:程序博客网 时间:2024/05/20 08:43
public class Solution {
public int threeSumClosest(int[] num, int target) {
if (num.length < 3)
return 0;
Arrays.sort(num);
int min = num[0] + num[1] + num[num.length - 1], sum, d;
for (int i = 0; i < num.length - 2; i++) {
int m = i + 1, j = num.length - 1;
if(i>0 && num[i] == num[i-1])
continue;
while (m < j) {
sum = num[i] + num[m] + num[j];
if (Math.abs(sum - target) < Math.abs(min - target)) {
min = sum;
if (sum == target)
return min;
}
if (sum > target)
j--;
else
m++;
}
}
return min;
}
public int threeSumClosest(int[] num, int target) {
if (num.length < 3)
return 0;
Arrays.sort(num);
int min = num[0] + num[1] + num[num.length - 1], sum, d;
for (int i = 0; i < num.length - 2; i++) {
int m = i + 1, j = num.length - 1;
if(i>0 && num[i] == num[i-1])
continue;
while (m < j) {
sum = num[i] + num[m] + num[j];
if (Math.abs(sum - target) < Math.abs(min - target)) {
min = sum;
if (sum == target)
return min;
}
if (sum > target)
j--;
else
m++;
}
}
return min;
}
}
-------------------------------------------
HINT:
确定其中一个,剩下的两个靠近; 记录每一次的和,随时替换。
=========================
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).
0 0
- 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
- [LeetCode] 3Sum Closest
- 【leetcode】3Sum Closest
- [LeetCode]3Sum Closest
- LeetCode-3Sum Closest
- LeetCode:3Sum Closest
- LeetCode | 3Sum Closest
- 【leetcode】3Sum Closest
- Leetcode: 3Sum Closest
- define宏定义中的#,##,@#及/符号
- 来安县新安镇人民政府 01wbjwxo
- gedit插件
- 癫痫病的治疗依据 01wty3sz
- 五个页面让你了解谷歌到底收集了什么个人信息
- *Leetcode - 3Sum Closest
- 癫痫病的最新疗法 01wvrt4c
- 癫痫病是什么病 01xas4pd
- Notification的用法也就有很多种
- TextView中使用SpannableString
- http://busumen.com/yulebagua/13595.html 01xsnmtc
- C# FileStream循环读取大文件数据
- Java正则表达式Pattern和Matcher
- http://www.zznews.cn/wenyi/ygf/ 020y1ogi