leetcode-15

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++)
{
// Skip duplicate elements
if (i > 0 && nums[i] == nums[i - 1])
continue;

// set two pointers
int lt = i + 1, rt = nums.size() - 1;
int target = -nums[i];

// set -nums[i] as target
// find the sum of two numbers
while (lt < rt)
{
int sum = nums[lt] + nums[rt];
if (sum == target)
{
result.push_back({nums[i], nums[lt], nums[rt]});
lt++;
rt--;
// Skip duplicate elements
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]]

  1. sort the array
    nums = [-4,-1,-1,0,1,2]

  2. set i = 0, lt = 1, rt = 5

  3. set target = -nums[i] = 4
    ……

  4. set i = 1, lt = 2, rt = 5

  5. set target = -nums[i] = 1

  6. set sum = nums[lt] + nums[rt] = -1 + 2 = 1

  7. set result.push_back([-1, -1, 2])

  8. set lt = 3, rt = 4

  9. set sum = nums[lt] + nums[rt] = 0 + 1 = 1

  10. set result.push_back([-1, 0, 1])

  11. set lt = 4, rt = 3

  12. end of loop

conclusion

Only this method is easy to understand…😥