3Sum Closest

来源:互联网 发布:whatsapp是什么软件 编辑:程序博客网 时间:2024/04/28 05:34
    public int threeSumClosest(int[] num, int target) {        // Start typing your Java solution below        // DO NOT write main() function        if(num.length < 3) return Integer.MIN_VALUE;        Arrays.sort(num);        int result = num[0] + num[1] + num[2];//pay attention here to initiate the result        for(int i = 0; i < num.length - 2; i++){            int start = i + 1;            int end = num.length - 1;            while(start < end) {                int sum = num[i] + num[start] + num[end];                     if(Math.abs(sum - target) < Math.abs(result - target)) result = sum;                if(sum == target) {                    result = target;                    return result;                }else if(sum < target) {                    start++;                }else {                    end--;                }            }        }        return result;    }

原创粉丝点击