[LeetCode] 3Sum Closest
算法渣,现实基本都参考或者完全拷贝[戴方勤(soulmachine@gmail.com)]大神的leetcode题解,此处仅作刷题记录。
1 class Solution { 2 public: 3 int threeSumClosest(vector<int> &num, int target) { 4 int result = 0; 5 int min_gap = INT_MAX; 6 7 sort(num.begin(), num.end()); // 排序 8 9 auto last = num.end(); 10 for (auto a = num.begin(); a < prev(last, 2); ++a) { 11 auto b = next(a); 12 auto c = prev(last); 13 while (b < c) { 14 const int sum = *a + *b + *c; 15 const int gap = abs(sum - target); 16 17 if (gap < min_gap) { 18 result = sum; 19 min_gap = gap; 20 } 21 22 if (sum < target) 23 ++b; 24 else 25 --c; 26 } 27 } 28 29 return result; 30 } 31 };