[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一样的想法,排序数组,先选一个数出来,再用target减去这个数,然后用找和为给定值的算法找最小差值,时间复杂度为O(n^2) , 要比枚举所有情况的O(n^3)来的快!
1 class Solution { 2 public: 3 int getDiff(vector<int> &num, int idx, int target) { 4 int low = idx, high = num.size() - 1; 5 int res = INT_MAX, tmp; 6 while (low < high) { 7 tmp = num[low] + num[high] - target; 8 res = abs(res) > abs(tmp) ? tmp : res; 9 if (tmp > 0) --high; 10 else if (tmp < 0) ++low; 11 else break; 12 } 13 return res; 14 } 15 16 int threeSumClosest(vector<int> &num, int target) { 17 int newtarget; 18 int diff = INT_MAX, tmp; 19 sort(num.begin(), num.end()); 20 for (int i = 0; i < num.size() - 2; ++i) { 21 newtarget = target - num[i]; 22 tmp = getDiff(num, i + 1, newtarget); 23 diff = abs(diff) > abs(tmp) ? tmp : diff; 24 } 25 return target + diff; 26 } 27 };