015.3Sum

Solution 1: skipped

Brute force with 3 loops, time complexity O(n^3)

Solution 2: accepted 58%

Two-pointer after sorting.

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
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int len = nums.length;
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (nums == null || len < 3)
return result;
Arrays.sort(nums);
for (int i = 0; i < len - 2; i++) {
if (i == 0 || nums[i] > nums[i - 1]) {
int j = i + 1;
int k = len - 1;
while (k > j) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == 0) {
List<Integer> al = new ArrayList<>();
al.add(nums[i]);
al.add(nums[j]);
al.add(nums[k]);
result.add(al);
j++;
k--;
while (k > j && nums[j] == nums[j - 1])
j++;
while (k > j && nums[k] == nums[k + 1])
k--;
}
else if (sum < 0)
j++;
else
k--;
}
}
}
return result;
}
}