LeetCode 3Sum Closest

Description: 

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.

Solution:

This problem is similar to the former one, but with slightly different.

This problem just asks us to calculate the closest number, which means we need to calculate every three number unless the three has been in the queue before. And in the 3Sum problem, one of the important optimizations is that once three number sum is 0, at most two sum is the same, both positive/negative, while the last one should be the opposite, that is negative/positive.

But this optimization under this circumstances is quite different. Because we want to find out the closest one, so no guarantee the three number should be obey.

In addition to this one, we can get the answer in simple way: for each number in the array, we start from the sum from rightmost and leftmost, then when the sum is smaller than target, leftmost index++; if greater, rightmost index--; if they are the same, then straightly return this sum.

import java.util.Arrays;

public class Solution {
	public int threeSumClosest(int[] nums, int target) {
		int min = 2 << 20 - target, ans = 0;
		int l, r, temp;
		Arrays.sort(nums);
		for (int i = 0; i < nums.length; i++) {
			if (i > 0 && nums[i] == nums[i - 1])
				continue;
			l = i + 1;
			r = nums.length - 1;
			while (l < r) {
				temp = nums[i] + nums[l] + nums[r];
				if (temp == target) {
					return target;
				} else if (temp < target) {
					l++;
					if (min > target - temp) {
						min = target - temp;
						ans = temp;
					}
				} else {
					r--;
					if (min > temp - target) {
						min = temp - target;
						ans = temp;
					}
				}
				// System.out.println("after  " + temp + "   " + (target + min)
				// + "  " + (target - min) + "   " + min);
			}
		}
		return ans;
	}

	public static void main(String[] args) {
		int[] arr = { 0, 0, 0 };
		int a = 1;
		Solution s = new Solution();
		System.out.println(s.threeSumClosest(arr, a));
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值