leetcode 16. 最接近的三数之和

leetcode

1,暴力法
C++:

class Solution {
public:
    int threeSumClosest(vector& nums, int target) {

        if ( nums.size() < 3 ) {

            return 0;
        }

        int closedTarget = nums[0] + nums[1] + nums[2];
        for ( int i = 0; i <= nums.size() - 3; ++i ) {

            for ( int j = i + 1; j <= nums.size() - 2; ++j ) {
                
                for ( int k = j + 1; k <= nums.size() - 1; ++k ) {
                    
                    int sum = nums[i] + nums[j] + nums[k];
                    if ( abs( sum - target ) < abs( closedTarget - target ) ) {

                        closedTarget = sum;
                    }
                }
            }
        }

        return closedTarget;
    }
};

2,排序 + 双指针
C++:

class Solution {
public:
    int threeSumClosest(vector& nums, int target) {

        if ( nums.size() < 3 ) {

            return 0;
        }

        std::sort(nums.begin(), nums.end());

        int result = nums[0] + nums[1] + nums[2];
        for ( int i = 0; i < nums.size(); ++i ) {

            int left = i + 1;
            int right = nums.size() - 1;
            while ( left < right ) {

                int sum = nums[i] + nums[left] + nums[right];
                if ( sum == target ) {

                    return target;
                }
                
                if ( sum > target ) {

                    --right;

                } else {

                    ++left;
                }

                if ( abs( sum - target ) < abs( result - target ) ) {

                    result = sum;
                }
            }
        }

        return result;
    }
};

你可能感兴趣的:(leetcode 16. 最接近的三数之和)