leetcode 16最接近的三数之和

 

 

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int res = nums[0]+nums[1]+nums[2];
        for(int i = 0;i<nums.size()-2;i++)
        {
            for(int j = i+1;j<nums.size()-1;j++)
            {
                for(int k = j+1;k<nums.size();k++)
                {
                    int value = nums[i]+nums[j]+nums[k];
                    int jueduizhi =  abs(target-value);
                    if (abs(target-res)>jueduizhi)
                    {
                        res =  value;
                    }
                }
            }
        }
        return res;
    }
};

 

posted @ 2021-10-26 17:56  A-inspire  Views(12)  Comments(0Edit  收藏  举报