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. Grunt学习日记

    Grunt和 Grunt 插件是通过npm安装并管理的, npm是Node.js的包管理器. 第一步:先安装node.js环境 第二步:安装Grunt-CLI 在node.js命令工具中输入npm i ...

  2. 7 Worksheet 对象

    7.1 设置阶段 代码清单7.1:使用Parent属性获得一个对象的父对象的指针 '使用Parent属性获得一个对象的父对象的指针 Sub MeetMySingleParent() 'Declare ...

  3. 关于Flask的默认session

    Flask的默认session利用了Werkzeug的SecureCookie,把信息做序列化(pickle)后编码(base64),放到cookie里了. 过期时间是通过cookie的过期时间实现的 ...

  4. [置顶][终极精简版][图解]Nginx搭建flv mp4流媒体服务器

    花了我接近3周,历经了重重问题,今日终于把流媒体服务器搞定,赶紧的写个博文以免忘记... 起初是跟着网上的一些教程来的,但是说的很不全面,一些东西也过时不用了(比如jwplayer老版本).我这次是用 ...

  5. bzoj3270

    3270: 博物馆 Time Limit: 30 Sec  Memory Limit: 128 MBSubmit: 474  Solved: 261[Submit][Status][Discuss] ...

  6. GitHub上README.md教程(copy)

    [说明:转载于http://blog.csdn.net/kaitiren/article/details/38513715] 最近对它的README.md文件颇为感兴趣.便写下这贴,帮助更多的还不会编 ...

  7. ipvs和ipvsadm

    ipvs和ipvsadm ipvs:内核中的协议栈上实现 ipvs是LVS软件核心,是运行在LB上的,这是个基于ip层的负载均衡. ipvs的总体结构主要有ip包处理,负载均衡算法,系统配置和管理三个 ...

  8. ODP.NET Managed 相关文章收集

      一.Oracle 对.net支持的一些基础知识了解介绍. 1.早年的时候,微软自己做的有 System.Data.OracleClient. 现在已经成了过期类了.性能等都不是很好. 2.Orac ...

  9. Java properties配置文件

    Java中的配置文件常为properties文件,格式为文本文件,文件内容的格式是“键=值”格式.注释信息使用“#”来注释. Properties类的常用方法 String getProperty(S ...

  10. E20170526-hm

    plain n. 平原; 平地;   adj. 平的; 素的; 清晰的; 相貌平平的; layout   n. 布局,安排,设计; 布置图,规划图; modularity    n. 模块化; 模块性 ...