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;
        }
    }
  • 相关阅读:
    BZOJ 1800 [Ahoi2009]fly 飞行棋
    BZOJ 3309 DZY Loves Math
    CAS Server和client 实现单点登录
    单点登录原理与简单实现
    Maven插件
    win10安装最新nexus-3.x及maven简单配置介绍
    oracle获取表的属性,包括字段,注释
    java 泛型详解-绝对是对泛型方法讲解最详细的,没有之一
    深入理解Tomcat虚拟目录
    环境搭建系列-系统安装之centos 6.5安装与配置
  • 原文地址:https://www.cnblogs.com/tobemaster/p/6012333.html
Copyright © 2011-2022 走看看