LeetCode 16. 最接近的三数之和

◇◆丶佛笑我妖孽 提交于 2020-03-06 22:09:17

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

 

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int i, j;
        int current_sum;
        int closet_sum = nums[0] + nums[1] + nums[2];

        sort(nums.begin(), nums.end());
        for (int k = 0; k < nums.size() - 2; ++k)
        {
            i = k + 1;
            j = nums.size() - 1;
            while (i < j)
            {
                current_sum = nums[k] + nums[i] + nums[j];
                if (abs(target - closet_sum) > abs(target - current_sum))
                    closet_sum = current_sum;
                if (target < current_sum)
                    --j;
                else if (target > current_sum)
                    ++i;
                else
                    return current_sum;
            }
        }

        return closet_sum;
    }
};

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!