首页 > 代码库 > 6.最接近的三数之和

6.最接近的三数之和

题目:给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。

 注意事项

只需要返回三元组之和,无需返回三元组本身

技术分享

class Solution {
public:
    /**
     * @param numbers: Give an array numbers of n integer
     * @param target: An integer
     * @return: return the sum of the three integers, the sum closest target.
     */
    int threeSumClosest(vector<int> nums, int target) {
        // write your code here
             int min = 0x7f7f;
        sort(nums.begin(), nums.end());
        int size = nums.size();
        for (int i = 0; i < size; i++) {
            int j = i + 1, k = size - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                if (abs(min - target) > abs(sum - target)) {
                    min = sum;
                }
                if (sum <= target) {
                    j++;
                } else {
                    k--;
                }
            }
        }
        return min;
    }
};

6.最接近的三数之和