[leetcode] 16.3Sum Closest

来源:互联网 发布:图片滚动播放软件 编辑:程序博客网 时间:2024/06/10 05:48

题目:
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).

题意:
给定一个数组,一个目标值,查找其中三个数相加起来与目标值最接近的值。
思路:
采用双指针求two-sum的方法。先将数组进行排序,花费时间复杂度是O(n)。从前往后依次选取数组中元素作为三个元素中的第一个元素num[i]。然后在num[i]后面的那些元素中使用two-sum的方法查找另外两个元素。双指针一开始一个指向num[i+1],一个指向num[size-1],如果当前三个元素求得的和与target更接近,那么我们更新结果为这三个数的和。并且调整指针,如果这三个元素之和小于目标值,那么将第一个指针往后移动,代表着增大这三个数的和,否则把后面的指针往前移动。
以上。
代码如下:

class Solution {public:    int threeSumClosest(vector<int> &num, int target) {        int size = num.size();        if (size < 3)            return 0;        else if (size == 3){            return num[0] + num[1] + num[2];        }        sort(num.begin(), num.end());        int result = num[0] + num[1] + num[2];        for (int i = 0; i < size; i++) {            int first = i + 1, second = size - 1;            while (first < second) {                int sum = num[i] + num[first] + num[second];                if (abs(sum - target) < abs(result - target)) {                    result = sum;                    if (result == target)return target;                }                (sum < target) ? first++ : second--;            }        }        return result;    }};
0 0
原创粉丝点击