Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
这个也是预处理排序,不过和15题不同的是它不需要跳过相同的数字,这两个数相加也是OK的。
class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int diff = 1 << 30; //初始设一个很大的数 sort(nums.begin(), nums.end()); int begin; int back = (int)nums.size() - 1; int cloestNum; for(begin = 0; begin < back; begin ++){ int front = begin + 1; back = (int)nums.size() - 1; while(front < back){ if(fabs(nums[begin] + nums[front] + nums[back] - target) < diff){ cloestNum = nums[front] + nums[back] + nums[begin]; diff = fabs(cloestNum - target); } if(diff == 0) return target; if(nums[front] + nums[back] + nums[begin] > target ) back --; else front ++; } while(begin+1 < back && nums[begin] == nums[begin + 1]) begin++; } return cloestNum; } };