LeetCode 3Sum Closest
2016-03-18 23:24
417 查看
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.
给出一组数以及一个目标值,从数组中选出3个数,他们的和最接近目标数,返回这3个数之和。
先给出代码
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int result=0;
int dis=Integer.MAX_VALUE;
Arrays.sort(nums);
int length=nums.length;
for(int i=0;i<length-2;++i){
for(int j=i+1,k=length-1;j<k;){
int sum=nums[i]+nums[j]+nums[k];
if(sum==target) return sum;
if(sum>target){
if(sum-target<dis){
dis=sum-target;
result=sum;
}
k--;
}
else{
if(target-sum<dis){
dis=target-sum;
result=sum;
}
j++;
}
}
}
return result;
}
}
将给的数组先用sort方法按升序排序,然后进行枚举。这样的时间复杂度是O(n^2)。
一开始的时候我采用了3个for的暴力枚举进行计算~结果超时了,,,leetcode上面运行时间的限制没具体说~ 还是越小越好吧
have exactly one solution.
给出一组数以及一个目标值,从数组中选出3个数,他们的和最接近目标数,返回这3个数之和。
先给出代码
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int result=0;
int dis=Integer.MAX_VALUE;
Arrays.sort(nums);
int length=nums.length;
for(int i=0;i<length-2;++i){
for(int j=i+1,k=length-1;j<k;){
int sum=nums[i]+nums[j]+nums[k];
if(sum==target) return sum;
if(sum>target){
if(sum-target<dis){
dis=sum-target;
result=sum;
}
k--;
}
else{
if(target-sum<dis){
dis=target-sum;
result=sum;
}
j++;
}
}
}
return result;
}
}
将给的数组先用sort方法按升序排序,然后进行枚举。这样的时间复杂度是O(n^2)。
一开始的时候我采用了3个for的暴力枚举进行计算~结果超时了,,,leetcode上面运行时间的限制没具体说~ 还是越小越好吧
相关文章推荐
- python标准库学习4-time
- 使用NDK生成native C/C++的可执行程序
- ldd -r xxx.so命令的重要作用------见招拆招地解决缺库问题(undefined symbol)
- 初学者必知的Python中优雅的用法
- uva624 - CD(01背包+打印路径)
- HDU-1160 FatMouse's Speed
- 高精度减法
- Android-在动作栏中添加和删除选项卡
- warning: target CPU does not support interworking
- 【POJ】[1703]Find them, Catch them
- Word文档分割总结
- C语言中的关键字
- CountDownLatch
- 在Ubuntu 14.04中升级python到2.7.11
- 2014蓝桥杯 地宫取宝 &&hdu 4597 四维数组状态记忆化
- Android中四大组件总结
- Java中String类(字符串操作)的10个常见问题和解决方法
- 多线程中跨线程访问的解决方法
- 在中国,程序员的职业生涯有多长?
- Java命名规范