zoukankan      html  css  js  c++  java
  • 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.

     
    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;
        }
    }
  • 相关阅读:
    openstack running 2
    openstack running 3
    好东西哟 XD
    Linux 上課用細部調整(转)
    openstack swift install 1
    Spring初识(通过小实例清晰认识Spring)
    Windowphone中如何将项目导出为模板
    WP8点击桌面图标快速恢复应用
    WindowsPhone8中SaveSong方法将音乐文件转存到音乐库中
    Windows Phone 数据绑定之UI Element Binding
  • 原文地址:https://www.cnblogs.com/tobemaster/p/6012333.html
Copyright © 2011-2022 走看看