zoukankan      html  css  js  c++  java
  • 【LeetCode】16. 3Sum Closest

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

    第一重循环先确定第一个数字,

    然后第二重循环用双指针分别从两端遍历,使得三个数的和不断接近target。

    若三个数的和等于target,则可以立即返回。

    时间复杂度:O(n2)

    class Solution {
    public:
        int threeSumClosest(vector<int> &num, int target) {
            sort(num.begin(), num.end());
            int size = num.size();
            int diff = INT_MAX;
            int ret;
            for(int i = 0; i < size; i ++)
            {
                int j = i + 1;
                int k = size - 1;
                while(j < k)
                {
                    int sum = num[i] + num[j] + num[k];
                    if(sum == target)
                        return target;
                    else if(sum < target)
                        j ++;
                    else
                        k --;
                    if(abs(sum - target) < diff)
                    {
                        diff = abs(sum - target);
                        ret = sum;
                    }
                }
            }
            return ret;
        }
    };

  • 相关阅读:
    MFC绘制直角坐标系
    mfc画波形函数
    ciscn_2019_ne_5
    ciscn_2019_n_5
    [ZJCTF 2019]NiZhuanSiWei
    ciscn_2019_n_1
    pwn-100
    2014提高组笔试错题
    BZOJ3211: 花神游历各国
    主席树模板
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4176327.html
Copyright © 2011-2022 走看看