天天看点

LeetCode-16.最接近的三数之和题目

题目

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

解题思路—双指针:这题与LeetCode-15.三数之和题目实际上算法核心是一样的,都是将三个数的一个数作为基准,另外两个数作为左右指针,向内遍历。要注意的是,题目中说明了每组输入只存在唯一答案,所以这题就不需要考虑数组中含有重复数字的情况,比第十五题少了很多判断条件。

Java解题—双指针

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int len = nums.length, min = Integer.MAX_VALUE;
        // 以最小的数为基准
        for(int i=0;i<len-2;i++){
            int left = i + 1, right = len - 1, sum = target - nums[i];
            while(left<right){
                int cha = sum - nums[left] - nums[right];
                if(cha==0) return target;
                if(Math.abs(cha)<Math.abs(min))
                    min = cha;
                if(cha>0)
                    left++;                  
                else
                    right--;
            }
        }
        return target-min;
    }
}