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

 

找到数组中跟目标数最接近的三个数的和 。

这里也是三个数的和问题,经过上一题三个数的和,这一题结果只有一个,也会有重复数字出现,需要处理,当然了,这里只要找到近似的和,不处理重复不影响结果。。
这里也是遍历数组,然后在剩下的数组中依次遍历(两端向中间),每次遍历都会产生一个三数之和,如果该和大于target,则需要右边指针向左移动,反之左边向右移动。同时也要判断此时的和与target之间的距离跟result与target之间距离的大小。

 

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        /**
        这里也是三个数的和问题,经过上一题三个数的和,这一题结果只有一个,也会有重复数字出现,需要处理,当然了,这里只要找到近似的和,不处理重复不影响结果。。
        这里也是遍历数组,然后在剩下的数组中依次遍历(两端向中间),每次遍历都会产生一个三数之和,如果该和大于target,则需要右边指针向左移动,反之左边向右移动。同时也要判断此时的和与target之间的距离跟result与target之间距离的大小。
        
        */
        //初始一个三个元素的和的变量,下面计算三个数的和时要和这个以及target之间的差值作比较
        int result=nums[0]+nums[1]+nums[nums.length-1];
        Arrays.sort(nums);
       
        
        
        for(int i=0;i<nums.length-2;i++){
            
                //两个数的和与sum最接近就行
                int left=i+1,right=nums.length-1;
                while(left<right){
                   int sum=nums[i]+nums[left]+nums[right];
                    if(sum>target) right--;
                    else left++;
                    if(Math.abs(result-target)>Math.abs(sum-target))
                        result=sum;
                    
                }
            
        }
        return result;
       
    }
}

 

 


posted on 2017-12-25 15:53  夜的第八章  阅读(176)  评论(0编辑  收藏  举报

导航