[leedcode 16] 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).

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        //本题是3Sum的变形,找出最接近target的值
        //跟3Sum唯一的不同是,需要增加一个变量min(注意初始化值),内层每次循环时,需要与它进行比较。保留住距离target最小的值
        //判断重复的逻辑可有可无,因为本题的输出只是需要返回总结果
        Arrays.sort(nums);
        int res=0;
        int min=Integer.MAX_VALUE;
        for(int i=0;i<nums.length;i++){
            int left=i+1;
           // if(i>0&&nums[i]==nums[i-1])continue;
            int right=nums.length-1;
            while(left<right){
                int temp=nums[i]+nums[left]+nums[right];//注意局部变量的声明,为后面的循环简化表达式
                if(temp==target)
                         return res=target;
                if(temp>target){
                    if(temp-target<min){
                        res=temp;
                        min=res-target;
                    }
                          
                    right--;
                }else{
                     if((target-temp)<min){
                          res=temp;
                          min=target-res;
                     }
                         
                    left++;
                }

            }
        }
        return res;
    }
}

 

posted @ 2015-07-07 11:27  ~每天进步一点点~  阅读(160)  评论(0编辑  收藏  举报