DEV Community

schudy
schudy

Posted on

LeetCode 15. 3Sum

I used two pointers to calculate the sum.
To better deduplicate the results, I sort the nums first. Then create a bland list as the returning result.

I enumerate the nums from the first one and the two pointers are going from left to right and right to left at the same time.

To deduplicate the first number, if nums[i] encounters the same value as previous one, just do nothing and move forward. Then calculate the value sum with the values of left index and the right index.

If the sum is greater than 0, then the right index can go left ward for a smaller value; if the sum smaller than 0, then we move the left index right ward to search a greater value. If the sum is 0, we append the triplet to the result. Then the left pointer move rightward. The right one we don't need to move it since it will move leftward if the sum > 0 automatically.

while to deduplicate the left index, if it finds the value is the same as the previous one, it will move rightward directly.

The corner cases are if the value of index i is greater than 0, then the sum cannot be zero anyway since the array already sorted. In this case, just break the for loop.
Alt Text

Top comments (0)