码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode #16 3Sum Closest (M)

时间:2015-10-10 00:10:43      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

[Problem]

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

[Analysis]

思路跟3Sum没有区别,只是输出变成了跟由集合内3个数字组合成与target差距最小的数。

 

[Solution]

import java.util.Arrays;

public class Solution {
    public int threeSumClosest(int[] num, int target) {
        int min = num[0] + num[1] + num[2];                
        Arrays.sort(num);
        
        for (int i = 0; i < num.length - 2; i++) {
            if (i > 0 && num[i] == num[i - 1]) {
                continue; // if current value is already tested as the first element, skip; 
            }
            
            // Do 2Sum
            int head = i + 1;
            int tail = num.length - 1;
            
            while (head < tail) {
                if (head > i + 1 && num[head] == num[head - 1]) {
                    head++;
                    continue; // if current value is already tested as the second, skip;
                }
                
                if (tail < num.length - 1 && num[tail] == num[tail + 1]) {
                    tail--;
                    continue; // similar test for the third element
                }
                
                int sum = num[i] + num[head] + num[tail];                
                
                if (sum == target) {
                    return sum;
                } else if (sum > target) {
                    tail--;
                } else {
                    head++;
                }
                
                if (Math.abs(sum - target) < Math.abs(min - target)) {
                    min = sum;
                }
            }
        }
        
        return min;
    }
}

 

LeetCode #16 3Sum Closest (M)

标签:

原文地址:http://www.cnblogs.com/zhangqieyi/p/4865445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!