LeetCode | 3Sum Closest

博客围绕LeetCode的3Sum Closest问题展开,给定整数数组和目标值,需找出数组中三个整数,使其和最接近目标值。介绍了Java解法思路,与3Sum类似,用变量记录和与目标值接近程度,根据和与目标值大小移动指针。

16. 3Sum Closest

Description

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).

Solution: (Java)
class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int gap = Integer.MAX_VALUE;
        int left, right, sum, result = 0;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length-2; i++) {
            if (i == 0 || nums[i] != nums[i-1]) {
                left = i + 1;
                right = nums.length - 1;
                while (left < right) {
                    sum = nums[i] + nums[left] + nums[right];
                    if (sum == target)
                        return sum;
                    else if (sum > target) {
                        right--;
                        while (left < right && nums[right] == nums[right+1]) {
                            right--;
                        }
                    } else {
                        left++;
                        while (left < right && nums[left] == nums[left-1]) {
                            left++;
                        }
                    }

                    if (Math.abs(sum - target) < gap) {
                        gap = Math.abs(sum - target);
                        result = sum;
                    }
                }
            }
        }

        return result;
    }
}
思路

题意为寻找三个数的和,使其最接近给定的target,本题思路与 LeetCode | 3Sum 类似,不一样的是:使用一个gap变量记录3个数的和与target的接近程度(即两者差的绝对值),寻找gap最小的那一组的和。还有就是left、right两个指针的移动:3个数的和大于target时,right指针向左移动;3个数的和小于target时,left指针向右移动。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值