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;
        }
    };

  • 相关阅读:
    HDU 1505 City Game
    HDU 1506 Largest Rectangle in a Histogram
    HDU 1838 Chessboard
    HDU 2512 一卡通大冒险
    HDU 1081 To The Max
    HDU 2845 Beans
    HDU 1422 重温世界杯
    HDU 1231 最大连续子序列
    第6章 接口和实现
    java面向抽象编程样例
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4176327.html
Copyright © 2011-2022 走看看