Leetcode 刷题: 3Sum Closest
2016-04-20 00:11
330 查看
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have
exactly one solution.
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int n= nums.length,res=0,diff=10000;;
if(n<3) return 0;
//Sort the array
Arrays.sort(nums);
res=nums[0]+nums[1]+nums[2];
for(int i=0;i<n-2;i++){
int j=i+1;
int k=n-1;
//using two pointer method
while(j<k){
if(Math.abs(nums[i]+nums[j]+nums[k]-target)<Math.abs(res-target)) {
res=nums[i]+nums[j]+nums[k];
}
if (nums[i]+nums[j]+nums[k]==target) return target;
else if(nums[i]+nums[j]+nums[k]<target)
j++;
else k--;
}
}
return res;
}
}
exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int n= nums.length,res=0,diff=10000;;
if(n<3) return 0;
//Sort the array
Arrays.sort(nums);
res=nums[0]+nums[1]+nums[2];
for(int i=0;i<n-2;i++){
int j=i+1;
int k=n-1;
//using two pointer method
while(j<k){
if(Math.abs(nums[i]+nums[j]+nums[k]-target)<Math.abs(res-target)) {
res=nums[i]+nums[j]+nums[k];
}
if (nums[i]+nums[j]+nums[k]==target) return target;
else if(nums[i]+nums[j]+nums[k]<target)
j++;
else k--;
}
}
return res;
}
}
相关文章推荐
- HDU 2202 最大三角形(求凸包中最大三角形面积)
- Mac 装 ITerm2 闪退
- 1020 of search
- ATL复合控件更换背景图
- 第5章 弹性及其应用
- linux数据结构—链表
- (JAVA)从零开始之--对象输入输出流ObjectInputStream、ObjectOutputStream(对象序列化与反序列化)
- HDU 1392 Surround the Trees(求凸包周长)
- POJ 3348 Cows(求凸包面积)
- Web Storage Session保存
- (19)Spring Boot 添加JSP支持【从零开始学Spring Boot】
- java环境变量 windows centos 安装jdk
- 关于php的crypt
- 特殊矩阵的压缩存储
- POJ 1228 Grandpa's Estate(确定凸包)
- 关于前端的思考与感悟
- 图片参数
- ASP.NET中HiddenField隐藏域控件的使用方法
- asp.net实现拒绝频繁的IP访问的方法
- ASP.NET中HyperLink超链接控件的使用方法