16. 3Sum Closest

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;
两个代码的思路其实都一样 先对数组进行排序 然后令第一个数加上后面两个数 依次对后面进行遍历 不知道为什么运行时间差这么大 求解释….

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值