16. 3Sum Closest(找出和最接近给定值的三个数)

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


题目大意:给定一个长度为n的整型数组和一个整数target,在数组中找出三个数,它们的和最接近target。可以认为对于每个测试用例,解决方案都是唯一的。

解题思路:类似《15. 3Sum(求数组中和为0的3个数)》,对于要求三个数的和,可以先对数组从小到大排序,然后锁定一个数nums[i],根据双指针的思路从数组两端到中间遍历,找到两个数nums[left]和nums[right],使得nums[left]+nums[right]+nums[i]的和最接近target。遍历过程中使用两个整数diff和res记录当前获得的最优解,其中res表示到目前为止找到的最接近target的三个数的和,diff表示target与res的差的绝对值。当遍历到res==target,已经是最佳方案了,直接返回。

解题代码:(22ms,beats 65.39%)

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int diff = Integer.MAX_VALUE;
		int res = 0;
		int len = nums.length;
		Arrays.sort(nums);
		for (int i = 0; i < len; i++) {
			int left = i + 1;
			int right = len - 1;
			while (left < right) {
				int sum = nums[i] + nums[left] + nums[right];
				if (sum == target) {
					return sum;
				}
				if (Math.abs(sum - target) < diff) {
					diff = Math.abs(sum - target);
					res = sum;
				}
				if (sum > target) {
					right--;
				} else {
					left++;
				}
			}
		}
		return res;
    }
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值