【Leetcode】16. 3Sum Closest 集合中选三个元素之和最接近指定值

1. 题目

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

2. 思路

先排序,遍历第一位。然后去查找符合要求的后两位。
后两位从头尾开始,向中间移动。如果结果偏小就移动小端,如果偏大就移动大端。找到整个移动过程中的最符合需求的数。
证明:第二个数为起点的所有pair中,最合适的一定的走到过的。

3. 代码

耗时:13ms

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int cv = target;
        int diff = numeric_limits<int>::max();
        for (int i1 = 0; i1 < nums.size() - 2; i1++) {
            int i2 = i1 + 1;
            int i3 = nums.size() - 1;
            while (i2 < i3) {
                int sum = nums[i1] + nums[i2] + nums[i3];
                int nd = abs(sum - target);
                if (nd == 0) return target;
                if (nd < diff) {
                    diff = nd;
                    cv = sum;
                }
                if (sum < target) {
                    i2++;
                } else {
                    i3--;
                }
            }
        }
        return cv;
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007276050
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞