Approach
Sorting and greedy selection
For Threesum2, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 45 lines of C++ from the credited upstream file threeSum2.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution {5 public:6 vector<vector<int> > threeSum(vector<int> &num) {7 vector<vector<int> > ans;8 const int target = 0;9 10 sort(num.begin(), num.end());11 auto last = num.rend();12 for(auto a = num.rbegin(); a < prev(last, 2); ++a) {13 if(a > num.rbegin() && *a == *(a - 1))14 continue;15 auto b = next(a);16 auto c = prev(last);17 18 while(b < c) {19 if(b > next(a) && *b == *(b - 1)) {20 ++b;21 }22 else if(c < prev(last) && *c == *(c + 1)) { 23 --c;24 }25 else {26 const int sum = *a + *b + *c;27 28 if(sum < target)29 --c;30 else if(sum > target)31 ++b;32 else {33 ans.push_back({ *c, *b, *a});34 ++b;35 --c;36 }37 }38 }39 }40 41 return ans;42 }43};44 45