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

3Sum Closest

时间:2016-10-30 07:25:42      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:numbers   3.2   str   代码   iss   value   array   style   alert   

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.

 
Example

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

不算是一道难题,可是硬生生把我的   Your submissions per problem 从3.2弄到了3.8(别看数据耀眼,因为还没刷几道题。。。)每次不是这组数据错就是另一组数据错

思路:类似2sum,2sum是两个指针两头逼近,这个无非是另外一个节点从头到尾遍历罢了,注意边界条件。

上代码

public class Solution {
    /**
     * @param numbers: Give an array numbers of n integer
     * @param target : An integer
     * @return : return the sum of the three integers, the sum closest target.
     */
    public int threeSumClosest(int[] numbers, int target) {
        Arrays.sort(numbers);
        int ans=Integer.MAX_VALUE;
        int anstemp;
        for(int i=0;i<numbers.length-2;i++){
            anstemp=Integer.MAX_VALUE;//这个每次for循环都要重置一下,因为上一次的anstemp会对当前的决策产生影响
            int j=i+1;//
            int k=numbers.length-1;//
            while(j<k){
                int temp=numbers[i]+numbers[j]+numbers[k];
                anstemp=witchclosezero(temp,anstemp,target);
                if(anstemp>target){
                    k--;//太大,后指针前移
                }else if(anstemp<target){
                    j++;//太小,前指针后移
                }else{
                    return anstemp;//等于直接返回
                }
            }
            ans=witchclosezero(anstemp,ans,target);//把当前层的anstemp保存下来,下一次for循环会重置
        }
        return ans;
    }
    public int witchclosezero(int A,int B,int t){//返回A,B中更接近t的那个
        int tempa=A-t;
        tempa=tempa>0?tempa:-tempa;
        int tempb=B-t;
        tempb=tempb>0?tempb:-tempb;
        return tempb>tempa?A:B;
    }
}

 

3Sum Closest

标签:numbers   3.2   str   代码   iss   value   array   style   alert   

原文地址:http://www.cnblogs.com/tobemaster/p/6012333.html

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