您的位置:首页 > 其它

LeetCode 3Sum Closest

2016-03-18 23:24 316 查看
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上面运行时间的限制没具体说~ 还是越小越好吧
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: