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.

Example:

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

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
 public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int sum = nums[0] + nums[1] + nums[2];
int diff = Math.abs(sum - target);
for (int i = 0; i < nums.length - 2; i++) {
if (i != 0 && nums[i] == nums[i - 1])
continue;
int j = i + 1;
int k = nums.length - 1;
while (k > j) {
int aa = nums[i] + nums[j] + nums[k];
int newDiff = Math.abs(aa - target);
if (newDiff < diff) {
diff = newDiff;
sum = aa;
}
if (aa < target) {
j++;
} else {
k--;
}
}
}
return sum;
}

LeetCode_16 3SumCloest的更多相关文章

随机推荐

  1. POJ 1625 Censored! (AC自己主动机 + 高精度 + DP)

    题目链接:Censored! 解析:AC自己主动机 + 高精度 + 简单DP. 字符有可能会超过128.用map映射一下就可以. 中间的数太大.得上高精度. 用矩阵高速幂会超时,简单的DP就能解决时间 ...

  2. flask的nocache防止js不刷新

    原文:http://librelist.com/browser/flask/2011/8/8/add-no-cache-to-response/#952cc027cf22800312168250e59 ...

  3. Android7.0源码编译运行指南【转】

    见连接: http://blog.csdn.net/HardReceiver/article/details/52650303

  4. 并不对劲的bjwc d4t1

    先膜一波宽神Orz%%%%% 拿到这题的第一反应就是:暴力啊!感觉神奇的钟点并没有什么性质,可能卡常能过吧……所以就写了一个O(22^3*59^3)的暴力.本来想打表,但是发现代码长度有限制,写不下. ...

  5. 移动前端第二弹:善用meta

    前言 在移动前端第一弹:viewport详解中,我们讲了viewport,那是一个关于meta的故事.这次我们会就将meta这个故事讲得更广阔.更有意思一些. 写过HTML的童鞋,应该都对这个不陌生, ...

  6. vue中子组件向父组件传值

    1.子组件$emit()触发,父组件$on()监听 子组件:<template> <div class="hello"> <button v-on:c ...

  7. P3297 [SDOI2013]逃考

    传送门 完全看不出这思路是怎么来的-- 首先对于两个亲戚,他们监视范围的边界是他们连线的中垂线.那么对于一个亲戚来说它能监视的范围就是所有的中垂线形成的半平面交 然后如果某两个亲戚的监视范围有公共边, ...

  8. 实数类型c++

    数据类型 定义标识符 数值范围 占字节数 有效位数 单精度浮点数 float -3.4E+38-3.4E+38 4(32位) 6-7位 双精度浮点数 double -1.7E+308-1.7E+308 ...

  9. CSMA/CA协议

    802.11中采用CSMA/CA协议来规定多个工作节点共用信道的问题. CSMA/CA的全称是Carrier sense multiple access with collision avoidanc ...

  10. svn报错:Cannot negotiate authentication mechanism

    在使用eclipse的svn插件连接osc的代码仓库时候,发生了以下错误: Cannot negotiate authentication mechanismsvn: Unable to connec ...