MrainW's Home

All things come to those who wait!

0%

LeetCode 15. 3Sum

Question

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

https://leetcode.com/problems/3sum/

  • Solution1
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
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
ArrayList<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length <= 2) return res;
int n = nums.length;
int i = 0;
Arrays.sort(nums);
while (i < n - 2) {
int base = nums[i];
int left = i + 1;
int right = n - 1;
while (left < right) {
int sum = base + nums[left] + nums[right];
if (sum == 0) {
List<Integer> list = new LinkedList<>();
list.add(base);
list.add(nums[left]);
list.add(nums[right]);
res.add(list);
left = moveRight(nums, left + 1);
right = moveLeft(nums, right - 1);
} else if (sum > 0) {
right = moveLeft(nums, right - 1);
} else {
left = moveRight(nums, left + 1);
}
}
i = moveRight(nums, i + 1);
}
return res;
}
private int moveLeft(int[] nums, int right) {
while (right == nums.length - 1 || (right >= 0 && nums[right] == nums[right + 1])) {
right--;
}
return right;
}
private int moveRight(int[] nums, int left) {
while (left == 0 || (left < nums.length && nums[left] == nums[left - 1])) {
left++;
}
return left;
}
}

Complexity:

Time complexity: O( n^2)

Space complexity: O(1)

Welcome to my other publishing channels