三数之和 II——LintCode
2015-12-11 13:02
501 查看
给一个包含n个整数的数组S, 找到和与给定整数target最接近的三元组,返回这三个数的和。
您在真实的面试中是否遇到过这个题?
Yes
样例
例如S = [-1, 2, 1, -4] and target = 1. 和最接近1的三元组是 -1
+ 2 + 1 = 2.
注意
只需要返回三元组之和,无需返回三元组本身
您在真实的面试中是否遇到过这个题?
Yes
样例
例如S = [-1, 2, 1, -4] and target = 1. 和最接近1的三元组是 -1
+ 2 + 1 = 2.
注意
只需要返回三元组之和,无需返回三元组本身
public class Solution { /** * @param numbers: Give an array numbers of n integer * @param target : An integer * @return : return the sum of the three integers, the sum closest target. */ public int threeSumClosest(int[] numbers ,int target) { // write your code here int min = Integer.MAX_VALUE, re=0; for(int i=0;i<numbers.length;i++) for(int j=i+1;j<numbers.length;j++) for(int k=j+1;k<numbers.length;k++) { int x = numbers[i] + numbers[j] + numbers[k] - target; if(x == 0) return target; if(x < 0) { x = -x; if(x < min ) { min = x; re = -x + target; } } else { if(x < min ) { min = x; re = x + target; } } } return re; } }
相关文章推荐
- Count Primes
- SPOJ COT Count on a tree
- APP原型设计工具,哪家强?转自知乎
- Cocos2d-x 脚本语言Lua基本语法
- 三数之和——LintCode
- rails 4 里面 用 link_to 来生成 delete调用,
- 十大编程算法助程序员走上高手之路
- Centos查看端口占用情况和开启端口命令
- Hadoop教程(四):理解MapReduce、MapReduce计数器和连接、MapReduce Hadoop程序连接数据
- MyEclipse提示注册码MyEclipse Trial Expired解决方案
- 派生类到基类的转换 和基类到派生类的转换
- linux硬链接与软链接
- Gson解析内存溢出
- 凸包 Codeforces605C Freelancer's Dreams
- Android学习笔记(15):网格布局GridLayout
- json_encode 数值类型转换
- Hadoop教程(三):HDFS、MapReduce、程序入门实践
- StoryBoard页面跳转方式 Show,Show Detail,Present Modally,Present as Popover
- 一起读 Gevent 源码
- Android学习笔记(14):相对布局RelativeLayout