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

LeetCode(16):3Sum Closest

时间:2016-01-26 20:15:16      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

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

题意:给定一个数组和目标元素,找出数组中的3个元素使其和最接近目标元素。

思路:首先对给定的数组进行排序,然后从0到数组元素长度len-2开始循环,对于每层循环,定义两个指针一个left指向i+1,right指向数组的尾部,然后开始判断i,left和start指向的元素之和是否更接近给定的元素,如果接近则更新,然后判断3个元素的和是大于给定的元素还是小于给定的元素,大于的话left指针加1,小于的话right指针减1;

代码:

public int threeSumClosest(int[] nums, int target) {
        int closest = nums[0] + nums[1] + nums[2];
        int diff = Math.abs(closest - target);
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            int start = i + 1;
            int end = nums.length - 1;
            while (start < end) {
                int sum = nums[i] + nums[start] + nums[end];
                int newDiff = Math.abs(sum - target);
                if (newDiff < diff) {
                    diff = newDiff;
                    closest = sum;
                }
                if (sum < target)
                    start++;
                else
                    end--;
            }
        }
        return closest;
    }

LeetCode(16):3Sum Closest

标签:

原文地址:http://www.cnblogs.com/Lewisr/p/5161386.html

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