首页 > 其他 > 详细

LeetCode - 3Sum Closest

时间:2015-12-07 15:37:37      阅读:211      评论:0      收藏:0      [点我收藏+]

题目:

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一样,排序之后,先确定第一个元素,然后对余下元素进行两边夹。

package sum;

import java.util.Arrays;

public class ThreeSumClosest {

    public int threeSumClosest(int[] nums, int target) {
        int len = nums.length;
        Arrays.sort(nums);
        
        int delta = nums[0] + nums[1] + nums[2] - target;
        for (int i = 0; i < len - 2;) {
            int l = i + 1;
            int r = len - 1;
            while (l < r) {
                int tmp = nums[i] + nums[l] + nums[r] - target;
                if (Math.abs(tmp) < Math.abs(delta))
                    delta = tmp;
                if (tmp == 0)
                    return target;
                if (tmp < 0)
                    ++l;
                else
                    --r;
            }
            
            do { ++i; } while (i < len && nums[i] == nums[i - 1]);
        }
        
        return target + delta;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] nums = { -1, 2, 1, -4 };
        int target = 1;
        ThreeSumClosest t = new ThreeSumClosest();
        System.out.println(t.threeSumClosest(nums, target));
    }

}

 

LeetCode - 3Sum Closest

原文:http://www.cnblogs.com/shuaiwhu/p/5025899.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!