16. 最接近的三数之和

16. 最接近的三数之和

给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums中选出三个整数,使它们的和与 target 最接近。

返回这三个数的和。

假定每组输入只存在恰好一个解。

 

 与15类似;

先对数组进行排序,然后遍历中使用双指针,时间复杂度为O(n^2);

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int res = nums[0] + nums[1] + nums[2];//这里要比较目标和三数之和的值,要初始化为较小的三个数
        int n = nums.size();
        for(int i = 0; i < n-2; i++){
            int l=i+1,r=n-1;
            while(l < r){
                int sum = nums[i] + nums[l] + nums[r];
                if(abs(target-res) > abs(target-sum)){//res距离目标较远
                    res = sum;
                }
                if(sum > target){//当前和大于目标,使其变小,右收缩
                    r--;
                }
                else if(sum < target){
                    l++;
                }
                else{
                    return target;
                }
            }
        }
        return res;
    }
};

 

posted @ 2023-01-13 23:11  陌初  阅读(25)  评论(0)    收藏  举报