3Sum Closest
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.
即给定一个数组 和 一个值 计算里面三个数相加最接近于给定的值的三个数的和;
因为比较简单所以直接进行代码比较
代码1:
public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int min_diff = Integer.MAX_VALUE;
for(int i=0; i<nums.length-2; ++i){
int p = i+1, q = nums.length-1;
while(p<q){
int diff = nums[i]+nums[p]+nums[q] - target;
if(diff == 0) return target;
min_diff = Math.abs(diff)<Math.abs(min_diff) ? diff: min_diff;
if(diff>0) --q;
else ++p;
}
}
return target + min_diff;
}
}
代码2:
public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closest=nums[0]+nums[1]+nums[2];
int low,high;
for(int i=0;i<nums.length-1;i++){
low=i+1;
high=nums.length-1;
while(low<high){
if(nums[low]+nums[high]==target-nums[i]) return target;
else if(nums[low]+nums[high]>target-nums[i]){
while(low<high&&nums[low]+nums[high]>target-nums[i]) high--;
if(Math.abs(nums[i]+nums[low]+nums[high+1]-target)<Math.abs(closest-target))
closest=nums[i]+nums[low]+nums[high+1];
}
else{
while(low<high&&nums[low]+nums[high]<target-nums[i]) low++;
if(Math.abs(nums[i]+nums[low-1]+nums[high]-target)<Math.abs(closest-target))
closest=nums[i]+nums[low-1]+nums[high];
}
}
}
return closest;
}
}
结果:代码1运行时间为16ms而代码2运行时间只为7ms;
两个代码的思路其实都一样 先对数组进行排序 然后令第一个数加上后面两个数 依次对后面进行遍历 不知道为什么运行时间差这么大 求解释….