1. 程式人生 > >LeetCode進階之路(3Sum Closest)

LeetCode進階之路(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).

題目:三個相加,求離目標值最近的和。

可以用3sum的思路來,先固定一個數,剩餘的頭尾遍歷,存最小值。但是這個思路超過時間限制,明天有空在研究下。

public static int threeSumCloest(int[] num , int target) {
		if(num == null || num.length<3) return 0;
		if(num.length == 3) return num[0] + num[1] + num[2];
		Arrays.sort(num);
		
		int min = Integer.MAX_VALUE;
		int length = num.length;
		int ret = 0;
		for(int i = 0;i < length-2;i++){
			int left = i+1;
			int right = length-1;
			if (i > 0 && num[i] == num[i-1]) continue;
			while(left < right) {
				int sum = num[i] + num[left] + num[right];
				if(sum < target) {
					if(target - sum < min) {
						min = target - sum;
						ret = sum;
					}
					left++;
				} else if (sum > target) {
					if(sum -target < min) {
						min = sum - target;
						ret = sum;
					}
					right--;
				} else {
					ret = sum;
				}
			}
		}
		return ret;
	}