15. 3Sum
Leetcode 15
I solved this problem using C++.
My idea: use two pointers to find the sum of three numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| class Solution { public: vector<vector<int>> threeSum(vector<int> &nums) { vector<vector<int>> result; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); i++) { if (i > 0 && nums[i] == nums[i - 1]) continue;
int lt = i + 1, rt = nums.size() - 1; int target = -nums[i];
while (lt < rt) { int sum = nums[lt] + nums[rt]; if (sum == target) { result.push_back({nums[i], nums[lt], nums[rt]}); lt++; rt--; while (lt < rt && nums[lt] == nums[lt - 1]) lt++; while (lt < rt && nums[rt] == nums[rt + 1]) rt--; } else if (sum < target) { lt++; } else { rt--; } } }
return result; } };
|
e.g.
nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
sort the array
nums = [-4,-1,-1,0,1,2]
set i = 0
, lt = 1
, rt = 5
set target = -nums[i] = 4
……
set i = 1
, lt = 2
, rt = 5
set target = -nums[i] = 1
set sum = nums[lt] + nums[rt] = -1 + 2 = 1
set result.push_back([-1, -1, 2])
set lt = 3
, rt = 4
set sum = nums[lt] + nums[rt] = 0 + 1 = 1
set result.push_back([-1, 0, 1])
set lt = 4
, rt = 3
end of loop
conclusion
Only this method is easy to understand…😥