LeetCode—— 最接近的三数之和
题目地址:https://leetcode-cn.com/problems/3sum-closest/
解题思路:和上一题三数之和类似(https://www.cnblogs.com/cc-xiao5/p/13392624.html),唯一的区别就是通过差的绝对值判断最接近
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int pa, pb, pc;//三个指针,代表三个数的位置 int len = nums.size(); int ans, tmp; sort(nums.begin(), nums.end()); ans = nums[0] + nums[1] + nums[2]; for (pa = 0; pa < len; pa++) { pc = len - 1; if (pa > 0 && nums[pa] == nums[pa - 1]) continue; for (pb = pa + 1; pb < len && pb < pc; pb++) { if (pb > pa + 1 && nums[pb] == nums[pb - 1]) continue; tmp = nums[pa] + nums[pb] + nums[pc]; while (pb < pc&&tmp> target) { //pc左移,使得总和变小 pc--; if (pb < pc) tmp = nums[pa] + nums[pb] + nums[pc]; ans = abs(ans - target) > abs(tmp - target) ? tmp : ans; } if (tmp < target)//pb右移,使得总和变大 ans = abs(ans - target) > abs(tmp - target) ? tmp : ans; else if (tmp == target) return target; } } return ans; } };