LeetCode第十六题(最接近的三数之和)

194 阅读1分钟

暴力解法(Java)

核心思想: 三层for循环计算所有三元组之和,从中选择一个最接近target的三数之和,不过也太暴力了,但结果很意外,居然没有超时。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int res = Integer.MAX_VALUE;//保存结果
        int res_abs = Integer.MAX_VALUE;//接近程度
        for(int i = 0; i < nums.length - 2; i++){
            for(int j = i + 1; j < nums.length - 1; j++){
                for(int k = j + 1; k < nums.length; k++){
                    int sum = nums[i] + nums[j] + nums[k];
                    if(res_abs > Math.abs(sum - target)){//接近程度的值越小越接近
                        res_abs = Math.abs(sum - target);
                        res = sum;
                    }
                }
            }
        }
        return res;
    }
}

排序+双指针(Java)

核心思想: 实际与LeetCode第十五题(三数之和)基本一致,实现代码有所不同,但核心思想不变。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);//对数组nums中的元素进行排序
        int res = Integer.MAX_VALUE;//保存结果
        int res_abs = Integer.MAX_VALUE;//接近程度
        for(int i = 0; i < nums.length - 2; i++){
            int left = i + 1;//左指针
            int right = nums.length - 1;//右指针
            while(left < right){
                int sum = nums[i] + nums[left] + nums[right];//三数之和
                if(res_abs > Math.abs(sum - target)){//接近程度的值越小越接近
                    res_abs = Math.abs(sum - target);
                    res = sum;
                }
                if(sum > target)//三数之和大于target,必须减小三数之和来接近target
                    right--;
                else if(sum < target)//三数之和小于target,必须增大三数之和来接近target
                    left++;
                else//三数之和等于target,已达最接近程度
                    return res;
            }
        }
        return res;
    }
}