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;
            }
      


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

  • 相关阅读:
    App性能测试工具-PerfDog
    痛并快乐着
    SQLyog连接MySQL的前前后后
    组合模式
    Java并发编程:线程池的使用
    高效能人事的七个习惯
    Spring中Bean的生命周期及其扩展点
    (转)第一次有人把“分布式事务”讲的这么简单明了
    分布式事物
    mybatis学习笔记(2)基本原理
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4629786.html
Copyright © 2011-2022 走看看