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

2022-07-26,,

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

  • 3 <= nums.length <= 10^3
  • -10^3 <= nums[i] <= 10^3
  • -10^4 <= target <= 10^4

示例

输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。

解题思路:

简化三个数求和,只要将其中一个数a作为固定数,位置为i,即依次遍历数组中各个数,作为固定数字,另外两个数b, c在[i + 1, n] 之间取值,使 a + b + c 与target相差最小。b初始位置为 i + 1, c初始位置为 n - 1。

  • 如果 a + b + c < target, b 位置 后移一位
  • 如果 a + b + c > target, c 位置 前进一位
  • 如果 a + b + c = target, 直接返回

如果是四个数求和,那么可以使用两层循环,取两个循环前1个数作为固定数,后续操作同上。

package com.alibaba.study.leetcode;

import java.util.Arrays;

/**
 * @Auther: wjj
 * @Date: 2020/12/7 17:03
 * @Description:
 */
public class LeetCode16 {

    public static void main(String[] args) {
        int[] nums = {-3,-2,-5,3,-4};
        int target = -1;
        System.out.printf("结果:" + threeSumClosest(nums, target));
    }

    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int count = nums.length;
        int sum = 1000;
        for(int i = 0; i< count - 2; i++){
            // 选取第一个数字作为基数
            int base = nums[i];
            // 第二数位置
            int pb = i + 1;
            // 第三个数位置
            int pc = count - 1;

            while (pb != pc){
                int tempSum = base + nums[pb] + nums[pc];
                if(Math.abs(sum - target) > Math.abs(tempSum - target)){
                    sum = tempSum;
                }
                if(tempSum < target){
                    pb ++;
                } else if(tempSum > target){
                    pc --;
                } else {
                    return tempSum;
                }
            }
        }
        return sum;
    }
}

本文地址:https://blog.csdn.net/Faker_Wang/article/details/110823961

《最接近的三数之和 - LeetCode第16题.doc》

下载本文的Word格式文档,以方便收藏与打印。