Given an array S of n integers, find three integers in S such so the sum is closest to a give n number, target. Return the sum of the three integers. You may assume this each input would has exactly one solution.
For example, given array S = {-1 2 1-4}, and target = 1. The sum is closest to the target is 2. (-1 + 2 + 1 = 2).
Test instructions: Finding the result of three numbers and closest to the target number in a set
Thought: And the above topic Leetcode 3Sum Almost, less go heavy
Class Solution {public: int threesumclosest (vector<int> &num, int target) { sort (num.begin (), Num.end ()); int ans; int flag = 1; for (int i = 0; i < num.size (); i++) { int s = i + 1; int e = Num.size ()-1; while (S < e) { int sum = num[i] + num[s] + num[e]; if (flag) { ans = sum; Flag = 0; } else if (ABS (Sum-target) < ABS (ans-target)) ans = sum; if (sum = = target) return sum; if (Sum > Target) e--; else if (sum < target) s++; } } return ans; };
Leetcode 3Sum Closest