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;
        }
    }
  • 相关阅读:
    关于Java中变量的意义和注意事项
    成为Android高手的十个建议
    成为Java高手的25个学习目标(经典)
    流体力学神器:Naiad 0.6 Windows版试用
    饭前念诵+感恩辞+感恩白開水
    Android 基本开发规范(必读)
    Python批量重命名Maya场景中的3D物体
    Java高新技术视频笔记:反射
    程序员编程技术迅速提高的终极攻略
    三十、有关联网问题
  • 原文地址:https://www.cnblogs.com/tobemaster/p/6012333.html
Copyright © 2011-2022 走看看