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

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));
	}
}

 

第二遍记录:

  Math.abs别忘记了。

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

 

 

 

 

posted @ 2014-06-26 19:20  jdflyfly  阅读(157)  评论(0编辑  收藏  举报