[leetcode] 3Sum Closest

这一生的挚爱 提交于 2021-02-12 13:30:28


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).
https://oj.leetcode.com/problems/3sum-closest/


思路1:类似3Sum,区别是不需要去重,另外需要维护一个最小差值。


import java.util.Arrays;

public class Solution {
	public int threeSumClosest(int[] num, int target) {
		int n = num.length;
		Arrays.sort(num);
		int min = Integer.MAX_VALUE;
		int result = 0;
		for (int i = 0; i < n; i++) {
			int start = i + 1, end = n - 1;
			int sum = target - num[i];
			int cur = 0;
			while (start < end) {
				cur = num[start] + num[end];
				if (Math.abs(cur + num[i] - target) < min) {
					min = Math.abs(cur + num[i] - target);
					result = cur + num[i];
				}
				if (cur < sum)
					start++;
				else if (cur > sum)
					end--;
				else {
					start++;
					end--;
				}
			}
		}
		return result;
	}

	public static void main(String[] args) {
		System.out.println(new Solution().threeSumClosest(new int[] { -1, 2, 1,
				-4 }, 1));
		System.out.println(new Solution().threeSumClosest(
				new int[] { 1, 2, 3, }, 100));
	}
}





标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!