LeetCode16 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. (Medium)
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).
分析:
排序、遍历方式顺序 与3 sum思路一致,维护一个与target的差值即可。
代码:
1 class Solution { 2 public: 3 int threeSumClosest(vector<int>& nums, int target) { 4 sort(nums.begin(), nums.end()); 5 int diff = 0x7FFFFFFF; 6 for (int i = 0; i < nums.size() - 2; ++i) { 7 int start = i + 1, end = nums.size() - 1; 8 while (start < end) { 9 int curSum = nums[i] + nums[start] + nums[end]; 10 if (curSum - target == 0) { 11 return target; 12 } 13 else if (curSum - target > 0) { 14 if (curSum- target < abs(diff) ) { 15 diff = curSum - target; 16 } 17 end--; 18 } 19 else { 20 if (target - curSum < abs(diff)) { 21 diff = curSum - target; 22 } 23 start++; 24 } 25 } 26 } 27 return diff + target; 28 } 29 };