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;
    }
};

posted @ 2017-08-06 16:57  Starry*sky  阅读(194)  评论(0编辑  收藏  举报