【LeetCode】3Sum Closest

来源:互联网 发布:qq截图软件绿色版 编辑:程序博客网 时间:2024/06/08 01:36

算法小白,最近刷LeetCode。希望能够结合自己的思考和别人优秀的代码,对题目和解法进行更加清晰详细的解释,供大家参考^_^

3Sum Closest

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).

题目的大概意思是说,找到三个数的和,其与给你的值差距最小,即绝对值最小,参考题目3Sum,给出O(n^2)的方法。

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        int res = nums[0] + nums[1] + nums[2];        int len = nums.size();        sort(nums.begin(), nums.end());        for (int i = 0; i < len; ++i){            int beg = i + 1, end = len - 1;            while (beg < end){                int sum = nums[i] + nums[beg] + nums[end]; // 计算三个数的和                res = abs(sum - target) < abs(res - target) ? sum : res; // 更新res                if (sum > target) --end;                else if (sum < target) ++beg;                else return res;  // 相等,直接返回            }        }        return res;    }};
0 0
原创粉丝点击