zoukankan      html  css  js  c++  java
  • 【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 };








  • 相关阅读:
    编程珠玑(续) 读书笔记 -(第三章 程序员的忏悔)
    java for循环
    java 中的 instanceof
    大脑学习
    voa 2015.4.29
    编程珠玑(续) 读书笔记 -(前言+第一章性能监视工具)
    voa 2015 / 4 / 27
    voa 2015 / 4 / 26
    背包问题 算法实现
    LCS 算法实现
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4251514.html
Copyright © 2011-2022 走看看