leetcode-3 closest

<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14.3999996185303px; line-height: 30px;">题目:Given an array <span style="box-sizing: border-box;">S</span> of <span style="box-sizing: border-box;">n</span> integers, find three integers in <span style="box-sizing: border-box;">S</span> 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.</p><pre style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13px; padding: 9.5px; margin-top: 0px; margin-bottom: 10px; line-height: 1.42857143; color: rgb(51, 51, 51); word-break: break-all; word-wrap: break-word; border: 1px solid rgb(204, 204, 204); border-radius: 4px; background-color: rgb(245, 245, 245);">    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[] num, int target) {
        int min=Integer.MAX_VALUE;
        int result=0;//the sum of the three number
        int len=num.length;
        Arrays.sort(num);
        for(int i=0;i<len-2;i++){
            int start=i+1;
            int end=len-1;
            int sum=target-num[i];
            while(start<end){
                int sum1=num[start]+num[end];
                int cur=Math.abs(sum1-sum);
                if(cur<min){
                    min=cur;
                    result=num[start]+num[i]+num[end];
                }
                if(sum1<sum)start++;
                if(sum1>sum)end--;
                if(sum1==sum)return result;
            }
            
        }
        return result;
    }
}

这个题目和3sum的很相似,需要注意的问题:

两个变量:一个min存和target的差值,一个result存储三个数的和。

这里的技巧:

一个排好序的数组,找两个数的和的一定值,用while循环从两端找起,同时方便调整大小。(注意只有剩下两个数的和才方便调整大小三个以上的数要用for循环)这个四个数4sum的题目会更加有体现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值