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. 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).
    

    Subscribe to see which companies asked this question

    class Solution {
    public:
        int threeSumClosest(vector<int> &num, int target) {
            int min = 999999;
            int size = num.size();
            sort(num.begin(), num.end());
            for (int i=0; i<size-2; i++)
            {
               if (i>0 && num[i] == num[i-1]) {
                   continue;
               }
               int j = i+1;
               int k = size - 1;
               while (j<k)
               {
                   int tmp = num[i]+num[j]+num[k];
                   if (tmp - target == 0)
                        return tmp;
                   else if (tmp - target < 0)
                   {
                       if (abs(tmp-target) < abs(min-target))
                        {
                            min = tmp;
                        }
                        j++;
                        while (num[j-1] == num[j]) {
                            j++;
                        }
                        
                   }
                   else
                   {
                        if (abs(tmp-target) < abs(min-target))
                        {
                            min = tmp;
                        }
                        k--;
                        while (num[k] == num[k+1]) {
                            k--;
                        }
                   }
                   
               }
            }
            return min;
        }
    };
  • 相关阅读:
    EFCore
    PS-邮件发送异常信息
    python-Django
    Autofac
    swagger
    查看哪个程序占用了端口
    SQL SERVER-系统数据库还原
    破解root密码
    WebApi路由
    async,await.task
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5100676.html
Copyright © 2011-2022 走看看