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差不多
class Solution { public: int threeSumClosest(vector<int> &num, int target) { sort(num.begin(),num.end()); int closet = num[0]+num[1]+num[2]; for(int i = 0 ; i < num.size()-2; ++ i){ int start = i+1, end = num.size()-1,sum = 0; while(start < end){ sum = num[i] + num[start] + num[end]; if(sum == target) return sum; else if(sum > target) end--; else start++; closet = abs(sum - target) < abs(closet-target) ? sum : closet; } } return closet; } };