【LeetCode】16. 3Sum Closest - Java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoguaihai/article/details/84200163

1. 题目描述:

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

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

2. 思路分析:

题目的意思是给定一个数组和一个目标数,找到数组中的3个数使得这3个数的和与目标数最接近(即:差的绝对值最小),并返回该3个数的和。

该题的思路类似3Sum的解法思路,但需要维护一个当前与目标值最近的值。

3. Java代码:

源代码见我GiHub主页

代码:

public static int threeSumClosest(int[] nums, int target) {
    Arrays.sort(nums);
    int minDistance = Integer.MAX_VALUE;
    int result = 0;
    for (int i = 0; i < nums.length; i++) {
        int left = i + 1;
        int right = nums.length - 1;
        while (left < right) {
            int threeSum = nums[i] + nums[left] + nums[right];
            if (threeSum == target) {
                return threeSum;
            }

            if (threeSum < target) {
                left++;
            }

            if (threeSum > target) {
                right--;
            }

            int curDistance = Math.abs(threeSum - target);
            if (curDistance < minDistance) {
                minDistance = curDistance;
                result = threeSum;
            }
        }
    }
    return result;
}

猜你喜欢

转载自blog.csdn.net/xiaoguaihai/article/details/84200163