LeetCode_16 3SumCloest
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的更多相关文章
随机推荐
- Run bash script as daemon
linux - Run bash script as daemon - Stack Overflow https://stackoverflow.com/questions/19233529/run- ...
- ubuntu下的root的创建进入与退出
创建: 在终端中输入:sudo passwd rootEnter new UNIX password: (在这输入你的密码)Retype new UNIX password: (确定你输入的密码)pa ...
- Ural1099 Work Scheduling 一般图的最大匹配
Ural1099 给定无向图, 求最大匹配. 在寻找增广路的过程中,可能出现一个奇环,这时候把奇环收缩,成为一朵“花”,并在新图上继续增广. 为了记录匹配关系,需要在花中寻找路径,每一条增广路径都可以 ...
- 洛谷 P2822 [ NOIP 2017 ] 组合数问题 —— 数学
题目:https://www.luogu.org/problemnew/show/P2822 阶乘太大,算不了: 但 k 只有 8 个质因子嘛,暴力60分: #include<iostream& ...
- win7安装oracle
1.下载 2.安装 主目录关键重要
- HTML和JSP的不同及优缺点
HTML(Hypertext Markup Language)文本标记语言,它是静态页面,和JavaScript一样解释性语言,为什么说是解释性语言呢?因为,只要你有一个浏览器那么它就可以正常显示出来 ...
- CSS中路径及form表单的用法
1.什么是路径? 路劲分为三种 1.绝对路径: 从盘符开始,然后依次的往下查找 本地: C:/Users/Administrator/Desktop/0527day01/07.html 服务器的: w ...
- RabbitMQ的一些基本操作
$ sudo chkconfig rabbitmq-server on # 添加开机启动RabbitMQ服务 $ sudo /sbin/service rabbitmq-server start # ...
- Laravel5.1学习笔记21 EloquentORM 集合
Eloquent: Collections Introduction Available Methods Custom Collections Introduction All multi-resul ...
- php angular/think angular/php模版引擎
在thinphp5中发现一个好用的模版引擎—think-angular, 此模板引擎主要特点是 不需要额外的标签定义, 全部使用属性定义, 写好的模板文件在IDE格式化代码的时候很整洁, 因为套完的模 ...