MCPcopy Create free account
hub / github.com/Ainevsia/Leetcode-Rust / threeSum

Method threeSum

15. 3Sum/Solution.cpp:15–36  ·  view source on GitHub ↗

just like 3 sum

Source from the content-addressed store, hash-verified

13
14 // just like 3 sum
15 vector<vector<int>> threeSum(vector<int>& nums) {
16 sort(nums.begin(), nums.end());
17 vector<vector<int>> res;
18 if (nums.size() < 3) return res;
19 for (int i=0; i<nums.size()-2; i++) {
20 if (i>0 and nums[i] == nums[i-1]) continue;
21 int l = i + 1, r = nums.size() - 1;
22 // find all the twoSums and don't duplicate
23 while (l < r) {
24 if (nums[l] + nums[r] + nums[i] == 0) {
25 res.push_back({nums[i], nums[l], nums[r]});
26 // prevent dup
27 while (l + 1 < nums.size() and nums[l+1] == nums[l]) l ++ ;
28 while (r - 1 >= 0 and nums[r-1] == nums[r]) r -- ;
29 l ++ ; r -- ;
30 }
31 else if (nums[l] + nums[r] + nums[i] < 0) l ++;
32 else if (nums[l] + nums[r] + nums[i] > 0) r --;
33 }
34 }
35 return res;
36 }
37};
38
39int main() {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected