Leetcode—16.最接近的三数之和【中等】

2023每日刷题(六十四)

Leetcode—16.最接近的三数之和

Leetcode—16.最接近的三数之和【中等】_第1张图片

实现代码

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int s = 0;
        int diff = INT_MAX / 2;
        int n = nums.size();
        int ans = 0;
        for(int i = 0; i < n - 2; i++) {
            int x = nums[i];
            if(i > 0 && x == nums[i - 1]) {
                continue;
            }
            int j = i + 1, k = n - 1;
            while(j < k) {
                s = x + nums[j] + nums[k];
                if(s == target) {
                    return s;
                } else if(s > target) {
                    if(s - target < diff) {
                        diff = s - target;
                        ans = s;
                    }
                    k--;
                } else if(s < target) {
                    if(target - s < diff) {
                        diff = target - s;
                        ans = s;
                    }
                    j++;
                }
            }
        }
        return ans;
    }
};

运行结果

Leetcode—16.最接近的三数之和【中等】_第2张图片
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,算法,职场和发展,c++,经验分享)