You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
To solve the 3Sum problem in Java using a `Solution` class, we'll follow these steps:
39
+
40
+
1. Define a `Solution` class with a method named `threeSum` that takes an array of integers `nums` as input and returns a list of lists representing the triplets that sum up to zero.
41
+
2. Sort the input array `nums` to ensure that duplicate triplets are avoided.
42
+
3. Initialize an empty list `result` to store the triplets.
43
+
4. Iterate over the elements of the sorted array `nums` up to the second to last element.
44
+
5. Within the outer loop, initialize two pointers, `left` and `right`, where `left` starts at the next element after the current element and `right` starts at the last element of the array.
45
+
6. While `left` is less than `right`, check if the sum of the current element (`nums[i]`), `nums[left]`, and `nums[right]` equals zero.
46
+
7. If the sum is zero, add `[nums[i], nums[left], nums[right]]` to the `result` list.
47
+
8. Move the `left` pointer to the right (increment `left`) and the `right` pointer to the left (decrement `right`).
48
+
9. If the sum is less than zero, increment `left`.
49
+
10. If the sum is greater than zero, decrement `right`.
50
+
11. After the inner loop finishes, increment the outer loop index while skipping duplicates.
51
+
12. Return the `result` list containing all the valid triplets.
0 commit comments