• 【Leetcode】【Medium】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).

    解题:

    数字求和问题,除了使用hash表使查找复杂度降为o(1)外,没有其他特别的方法。基本的思路都是枚举某一个数,然后计算余下的数字组合;

    本题先对数组进行排序,然后以某一个数为基准,设置两个指针从两头操作余下的数,计算三数的和,如果和大于target,右指针左移,反之,左指针右移。期间不断记录离target最近的sum值。

    总时间复杂度o(nlogn) + o(n2) = o(n2)

    需要用到C++ abs函数,求绝对值。

    代码:

    (由于题目中说一定存在一个答案,因此省略判断某些边界情况)

     1 class Solution {
     2 public:
     3     int threeSumClosest(vector<int> &num, int target) {
     4         sort(num.begin(), num.end());
     5         int size = num.size();
     6         int min_gap = INT_MAX;
     7         
     8         for (int i = 0; i < size; ++i) {
     9             int j = i + 1;
    10             int k = size - 1;
    11             
    12             while (j < k) {
    13                 int cur_gap = num[i] + num[j] + num[k] - target;
    14                 if (abs(cur_gap) < abs(min_gap))
    15                     min_gap = cur_gap;
    16                     
    17                 if (cur_gap > 0)
    18                     --k;
    19                 else if (cur_gap < 0)
    20                     ++j;
    21                 else
    22                     return target;
    23             }
    24         }
    25         
    26         return target + min_gap;
    27     }
    28 };








  • 相关阅读:
    多输出感知机及其梯度
    《机器学习实战》-线性回归
    《机器学习实战》-逻辑(Logistic)回归
    SQL Server 空间监测
    SQL Server 从数据库快照还原数据库
    SQL Server 创建数据库快照
    SQL Server 数据库的自动选项
    SQL Server 数据库游标选项
    SQL Server 数据库状态选项
    MYSQL 二进制还原
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4251514.html
Copyright © 2020-2023  润新知