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. 【bzoj2282】[Sdoi2011]消防

    两次bfs可得直径,答案一定不会小于所有点到直径的距离最大值,只要把直径上的边权设为0,任选直径上一点bfs可得将最大值作为二分下界,二分直径左右端点的舍弃部分 #include<algorit ...

  2. 单独编译framework【转】

    本文转载自:http://blog.csdn.net/u011168565/article/details/53782325 参考文章: http://bbs.csdn.net/topics/3701 ...

  3. 在java中除去字符串(String)中的换行字符(\r \n \t)

    我们先来看几个例子: 例1: public class Test { public static void main(String[] args) { String s = "'sds gd ...

  4. USACO Section 1.2PROB Transformations

    挺有趣的一道题,呵呵,不算难 /* ID: jusonal1 PROG: transform LANG: C++ */ #include <iostream> #include <f ...

  5. 如何装载Storyboard中的ViewController?

      如上图所示,如何装载Storyboard中指定的ViewController? 首先,需要指定ViewController的ID,如上图右上方红色方框内的Storyboard ID.然后使用下面的 ...

  6. jsp制作登录正在加载页面.....

    1. <body style="margin:0px;"> <div id="loading"> <div class=" ...

  7. 【174】C#添加非默认字体

    参考:C# WinForm程序安装字体或直接调用非注册字体 参考:百度知道 在Debug文件夹下面新建一个font的文件夹,然后将字体的文件复制到里面,使用的时候,直接调用字体文件! private ...

  8. springboot根据yml配置文件选择性加载bean

    @Slf4j @Aspect @Component @ConditionalOnProperty(value = "localCache.apiCache", havingValu ...

  9. git回到没push的commit

    创建: 2017/10/28   merge master以后数据库出了问题,改好以后发现view有点问题,commit以后没提交就reset了.过后才想起来怎么回去???吓成狗,索性找到了下面这个. ...

  10. js工作备注

    { field : 'state', title : '事件状态', align: 'center', width : 120, formatter : function(value, row, in ...