LeetCode 16 3Sum Closest

来源:互联网 发布:淘宝开店书籍 编辑:程序博客网 时间:2024/06/03 18:22

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

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.


解题思路: 这道题的基本实现方法与3-sum一致,而且更为简单。只要找到最接近target那个数即可。实现方法为,记录每次的求和的结果,返回最小值。我一开始很天真的把3-sum的实现拿过来随便修改一下就提交了,结果狠狠地打了我的脸,因为3-sum中重复性判断的语句并不适用于3-sum closest。因为两者的边界条件并不一致,只有当出现完全等于target的时候,才会出现重复性判断,而closest找到一个接近值的时候就已经触发重复性判断,这样会导致错过那个更接近的值。因此,在消除重复性逻辑判断以后,符合题目要求。
比如 {20 -19 -19 -18 -18} -59,若按照原来的重复性判断,结果会是-57,而实质上的最接近值为-58,因为当指针指向-19的时候由于重复性判断,start和end都指向同一个-19这时start已经==end了,跳出循环,错过最接近值。因此,需要消除重复性判断。


代码如下:

public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int len =nums.length; int min =Integer.MAX_VALUE;//记录最小的reint d =Integer.MAX_VALUE;//记录当前最小的差值for (int i = 0; i < len-2; i++) {//len-2已经包含所有情况if(i>0&&nums[i]==nums[i-1])continue;//这里是i-1与i的判断因为for循环i++了    int start =i+1;    int end = len-1;int s = nums[i];    while(start<end){int re = s +nums[start]+nums[end];int t = Math.abs(re - target);if(t<=d){min = re;d = t; }if(re>target){end--;              //while (start < end && nums[end] == nums[end-1]) end--; //消除的重复性判断}else if(re<target){start++;// while (start < end && nums[start] == nums[start+1]) start++;  //消除的重复性判断}else{return min;}    }} return min;    }


0 0
原创粉丝点击