美文网首页
3Sum Closest

3Sum Closest

作者: 走地牙 | 来源:发表于2018-07-11 23:41 被阅读0次

/*

1 遍历整个数组

2 起始点和结束点 从前后往中间遍历

3 比较和与target的差值 小的存入结果当中

注意 ans 初始值不能付最大 ;

*/

class Solution {

    public int threeSumClosest(int[] nums, int target) {

        if(nums == null || nums.length < 3) return -1;

        Arrays.sort(nums);

        int ans = nums[0] + nums[1] + nums[2];

        for(int i = 0; i < nums.length - 2; i++) {

            int start = i + 1;

            int end = nums.length - 1;

            while(start < end) {

                int sum = nums[i] + nums[start] + nums[end];

                if(Math.abs(sum - target) < Math.abs(ans - target)) {

                    ans = sum;

                }

                if(sum > target) {

                    end--;

                } else if (sum < target) {

                    start++;

                } else {

                    return target;

                }

            }

        }

        return ans;

    }

}

相关文章

网友评论

      本文标题:3Sum Closest

      本文链接:https://www.haomeiwen.com/subject/vmokpftx.html