LeetCode刷题(C++)——3Sum Closest(Medium)

来源:互联网 发布:淘宝能买哪些虚拟产品 编辑:程序博客网 时间:2024/06/16 14:19

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这道题,在3Sum那道题的基础上稍微修改一下即可http://blog.csdn.net/yf_li123/article/details/71176581

class Solution {public:    int threeSumClosest(vector<int>& nums, int target) {        sort(nums.begin(), nums.end());int closest = INT_MAX;int ans = 0;for (int start = 0; start < nums.size();start++){int i = start + 1;int j = nums.size() - 1;while (i < j){int sum = nums[i] + nums[j] + nums[start];if (sum == target)return target;else if (sum < target){if ((target - sum) < closest){closest = target - sum;ans = sum;}while (i + 1 < nums.size() && nums[i] == nums[i + 1])i++;i++;}else{if ((sum - target) < closest){closest = sum - target;ans = sum;}while (j - 1 >= 0 && nums[j] == nums[j - 1])j--;j--;}}while (start + 1 < nums.size() && nums[start] == nums[start + 1])start++;}return ans;    }};


0 0
原创粉丝点击