16. 3Sum Closest

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

解析


// three sum closest
class Solution_16 {
public:
    // 三个指针操作O(N^2) test=([0,2,1,-3] 1);([1,1,-1,-1,3]-1)
    int threeSumClosest(vector<int>& nums, int target) {
        if (nums.size() < 3)
        {
            return 0;
        }

        int closest_sum = nums[0] + nums[1] + nums[2];
        sort(nums.begin(), nums.end());
        for (int first = 0; first < nums.size() - 2; first++)
        {
            if (first > 0 && nums[first] == nums[first - 1])
            {
                continue;
            }
            int second = first + 1;
            int end = nums.size() - 1;
            while (second<end)
            {
                int temp = nums[first] + nums[second] + nums[end];

                if (abs(closest_sum - target)>abs(temp - target))
                {
                    closest_sum = temp;
                }
                if (temp == target)
                {
                    return temp;
                }
                else if (temp < target)
                {
                    second++;
                }
                else
                {
                    end--;
                }
            }
        }
        return closest_sum;
    }

    // 暴力O(n^3)
    int threeSumClosest_1(vector<int> &num, int target)
    {
        int res = num[0] + num[1] + num[2];
        for (int i = 0; i < num.size() - 2; i++){
            for (int j = i + 1; j < num.size() - 1; j++){
                for (int t = j + 1; t < num.size(); t++){
                    int tem = num[i] + num[j] + num[t];
                    if (abs(target - tem) < abs(target - res))
                        res = tem;
                    if (res == target)
                        return res;
                }
            }
        }
        return res;
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8322222.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞