problem

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

1
2
3
4
5
6
7
Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

approach 1

算法

暴力解法,3 层循环

复杂度

  • time:O(n^3)
  • space:O(1)

approach 2

算法

2 层+set

复杂度

  • time:O(n^2)
  • space:O(n)

approach 3

算法

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
class Solution {
public static List<List<Integer>> threeSum(int[] nums) {

if (nums == null || nums.length < 3) {
return Collections.EMPTY_LIST;
}

Set<List<Integer>> res = new HashSet<>();

Arrays.sort(nums);

for (int i = 0; i < nums.length - 2; i++) {
if (i >= 1 && nums[i] == nums[i - 1]) {
continue;
}
Set<Integer> set = new HashSet<>();
for (int j = i + 1; j < nums.length; j++) {
if (set.contains(nums[j])) {
res.add(Arrays.asList(nums[i], (-nums[i] - nums[j]), nums[j]));
set.remove(nums[j]);
} else {
set.add(-nums[i] - nums[j]);
}

}

}

return new ArrayList<>(res);
}

}

复杂度

  • time:O()
  • space:O()

summery


Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×