zoukankan      html  css  js  c++  java
  • [leetcode]3 Sum 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).
    

    基本思路:

    本题能够利用上一篇《3 Sum》同样的思路来处理。就是对数组排序,然后利用数字之间的序关系降低对不必要情况的处理。


    代码:

    int threeSumClosest(vector<int> &num, int target)   //C++
        {
            //You may assume that each input would have exactly one solution.
            int sum = num[0]+num[1]+num[2];
            int dif = abs(sum -target);
            
            sort(num.begin(), num.end());
            for (int i = 0; i < num.size() - 2;)
            {
                int l = i + 1, r = num.size() - 1;
                while (l < r)
                {
                    int tmpdif = num[l] + num[r] + num[i] - target;
                    if ( tmpdif <= -dif) l++;
                    else if (tmpdif > -dif && tmpdif < dif)
                    {
                        dif = abs(tmpdif);
                        sum = num[l] + num[r] + num[i];
                        if(tmpdif < 0)
                            do { l++; }while (l < r && num[l - 1] == num[l]);
                        else if(tmpdif > 0)
                            do { r--; }while (l < r && num[r + 1] == num[r]);
                        else return target;
                    }
                    else r--;
                }
                do{ i++; }while (i < num.size() - 1 && num[i - 1] == num[i]);
            }
            return sum;
            }
      


    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    hdu4990矩阵快速幂
    预处理+状态压缩+剪枝——codefoece 1209E
    AC自动机处理多串匹配——cf1202E
    二维差分前缀和——cf1202D(好题)
    序列递推——cf1204E(好题)
    建模+线性dp——cf1201D
    暴力——cf1202C
    经典排序背包——cf1203F
    思维+贪心——cf1042D
    分块——cf1207F
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4629786.html
Copyright © 2011-2022 走看看