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

xiaoxiao2021-02-27  243

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

转载请注明原文地址: https://www.6miu.com/read-8511.html

最新回复(0)