zoukankan      html  css  js  c++  java
  • LeetCode OJ

    题目:

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

    解题思路:

    枚举第一个数,另外两个数:一个在第一个数后边一个开始,一个从末尾开始,和4Sum类似调整。复杂度:O(n^2)。

    代码:

     1 class Solution {
     2 public:
     3     int threeSumClosest(vector<int> &num, int target) {
     4        int ans = 0;
     5        bool findans = false;
     6        sort(num.begin(), num.end());
     7        for (int first = 0; first < num.size(); first++){
     8            for (int second = first + 1, third = num.size() - 1; second < third; ){
     9                int tmp_sum = num[first] + num[second] + num[third];
    10                if (tmp_sum < target){
    11                    second ++;
    12                }
    13                if (tmp_sum > target){
    14                    third --;
    15                }
    16                if (tmp_sum == target){
    17                    return tmp_sum;
    18                }
    19                
    20                if (!findans || (abs(tmp_sum - target) < abs(ans - target))){
    21                    ans = tmp_sum; 
    22                    findans = true;
    23                }
    24            }
    25        }
    26        return ans;
    27     }
    28 }; 
  • 相关阅读:
    软件测试人员的要求
    冒烟测试和回归测试的区别
    [go]struct
    [go]socket编程
    [go]gorhill/cronexpr用go实现crontab
    [go]os/exec执行shell命令
    [go]time包
    [go]etcd使用
    [go]redis基本使用
    [go]go操作mysql
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3788809.html
Copyright © 2011-2022 走看看