# [15\. 3Sum](https://leetcode.com/problems/3sum/) :::spoiler Solution ```cpp= class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<vector<int>> res; for (int i = 0; i < nums.size(); i++) { if (i > 0 && nums[i - 1] == nums[i]) continue; int left = i + 1, right = nums.size() - 1; while (left < right) { int threeSum = nums[i] + nums[left] + nums[right]; if (threeSum < 0) left++; else if (threeSum > 0) right--; else { res.push_back({nums[i], nums[left], nums[right]}); left++; right--; while (left < right && nums[left - 1] == nums[left]) left++; while (left < right && nums[right + 1] == nums[right]) right--; } } } return res; } }; ``` - T: $O(N^2)$ - S: $O(\log N)$ :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up