| 1 | class Solution { |
| 2 | public: |
| 3 | vector<vector<int>> threeSum(vector<int>& nums) { |
| 4 | vector<vector<int> > res; |
| 5 | |
| 6 | std::sort(nums.begin(), nums.end()); |
| 7 | |
| 8 | for (int i = 0; i < nums.size(); i++) { |
| 9 | |
| 10 | int target = -nums[i]; |
| 11 | int front = i + 1; |
| 12 | int back = nums.size() - 1; |
| 13 | |
| 14 | while (front < back) { |
| 15 | |
| 16 | int sum = nums[front] + nums[back]; |
| 17 | |
| 18 | // Finding answer which start from number nums[i] |
| 19 | if (sum < target) |
| 20 | front++; |
| 21 | |
| 22 | else if (sum > target) |
| 23 | back--; |
| 24 | |
| 25 | else { |
| 26 | vector<int> triplet(3, 0); |
| 27 | triplet[0] = nums[i]; |
| 28 | triplet[1] = nums[front]; |
| 29 | triplet[2] = nums[back]; |
| 30 | res.push_back(triplet); |
| 31 | |
| 32 | // Processing duplicates of Number 2 |
| 33 | // Rolling the front pointer to the next different number forwards |
| 34 | while (front < back && nums[front] == triplet[1]) front++; |
| 35 | |
| 36 | // Processing duplicates of Number 3 |
| 37 | // Rolling the back pointer to the next different number backwards |
| 38 | while (front < back && nums[back] == triplet[2]) back--; |
| 39 | } |
| 40 | |
| 41 | } |
| 42 | |
| 43 | // Processing duplicates of Number i |
| 44 | while (i + 1 < nums.size() && nums[i + 1] == nums[i]) |
| 45 | i++; |
| 46 | |
| 47 | } |
| 48 | |
| 49 | return res; |
| 50 | } |
| 51 | }; |
nothing calls this directly
no outgoing calls
no test coverage detected