16. 3Sum Closest LeetCode题解

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Subscribe to see which companies asked this question.

题意:

给定一个整数数组S,在S中寻找三个整数,使得其和最接近给定的数字,目标。返回这三个整数的和。每个样例至少包含一个解。


题解:

这道题的思路与3sum完全一致;

如果可以事先确定三个数中的一个值,那么题目变成2sum问题;

而事先确定的方法就是枚举数组中的所有值。


Code【Java】

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        // 数组排序 初始化结果
        Arrays.sort(nums);
        int ans = nums[0] + nums[1] + nums[2];
        // 选定一个数,然后剩余值进行2sum
        for (int i = 0; i < nums.length - 2; ++i) {
            for (int lo = i + 1, hi = nums.length - 1; lo < hi;) {
                int val = nums[i] + nums[lo] + nums[hi];
                // 更新结果
                if (Math.abs(target - val) < Math.abs(target - ans)) {
                    ans = val;
                }
                if (val == target) {
                    return target;
                } else if (val < target) {
                    lo++;
                } else {
                    hi--;
                }
            }
        }
        return ans;
    }
}


Code【C++】

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        // 数组排序 初始化结果
        sort(nums.begin(), nums.end());
        int ans = nums[0] + nums[1] + nums[2];
        // 选定一个数,然后剩余值进行2sum
        for (int i = 0; i < nums.size() - 2; ++i) {
            for (int lo = i + 1, hi = nums.size() - 1; lo < hi;) {
                int val = nums[i] + nums[lo] + nums[hi];
                // 更新结果
                if (abs(target - val) < abs(target - ans)) {
                    ans = val;
                }
                if (val == target) {
                    return target;
                } else if (val < target) {
                    lo++;
                } else {
                    hi--;
                }
            }
        }
        return ans;
    }
};


猜你喜欢

转载自blog.csdn.net/baidu_23318869/article/details/72594149