LeetCode-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.

    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[] nums, int target) {
        int diff=Integer.MAX_VALUE;
        int res=0;
        if(nums==null && nums.length==0){
            return 0;
        }
        Arrays.sort(nums);
        int len=nums.length;
        for(int i=0; i<len-2; i++){
            if(!(i>0 && nums[i]==nums[i-1])){
                int sum=getSum(nums, i, target);
                if(Math.abs(target-sum)<diff){
                    diff=Math.abs(target-sum);
                    res=sum;
                }
            }
        }
        return res;
    }
    public int getSum(int[] nums, int index, int target){
        
        int first=nums[index];
        int left=index+1;
        int right=nums.length-1;
        int diff=Integer.MAX_VALUE;
        int res=0;
        while(left<right){
            boolean valid=true;
            if(left>index+1 && nums[left]==nums[left-1]){
                left++;
                valid=false;
            }
            if(right<nums.length-1 && nums[right]==nums[right+1]){
                right--;
                valid=false;
            }
            if(valid){
                int sum=first+nums[left]+nums[right];
                if(Math.abs(target-sum)<diff){
                    diff=Math.abs(target-sum);
                    res=sum;
                }
                if((target-sum)>=0){
                    left++;
                }
                else{
                    right--;
                }
            }
        }
        return res;
    }
}

优质内容筛选与推荐>>
1、xCode如何导入自定义的snippets文件
2、在SQL Server 2005中实现表的行列转换()
3、Driver驅動模式-Sec-06
4、for in语句与for in语句输入顺序问题
5、oracle在cmd中启动数据库实例


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn