Repository navigation
Expand file tree
/
Copy pathSolution.java
More file actions
77 lines (73 loc) · 2.21 KB
/
Copy pathSolution.java
File metadata and controls
77 lines (73 loc) · 2.21 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.q0015_3sum;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author xjn
* @since 2020-01-20
* 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
* <p>
* 注意:答案中不可以包含重复的三元组。
* 示例:
* <p>
* 给定数组 nums = [-1, 0, 1, 2, -1, -4],
* <p>
* 满足要求的三元组集合为:
* [
* [-1, 0, 1],
* [-1, -1, 2]
* ]
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/3sum
* 时间复杂度 O(n^2)
* 空间复杂度O(n)
*/
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//O(log(n))
Arrays.sort(nums);
List<List<Integer>> lists = new ArrayList<>();
//O(n^2)
for (int i = 0; i < nums.length; i++) {
int l = i + 1;
int r = nums.length - 1;
//s[l...r]
if (nums[i] > 0) {
break;
}
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
while (l < r) {
List<Integer> list = new ArrayList<>();
if (nums[i] + nums[l] + nums[r] == 0) {
list.add(nums[i]);
list.add(nums[l]);
list.add(nums[r]);
while (l < r && nums[l] == nums[l + 1]) {
l++;
}
while (l < r && nums[r] == nums[r - 1]) {
r--;
}
l++;
r--;
} else if (nums[i] + nums[l] + nums[r] > 0) {
r--;
} else if (nums[i] + nums[l] + nums[r] < 0) {
l++;
}
if (!list.isEmpty()) {
lists.add(list);
}
}
}
return lists;
}
public static void main(String[] args) {
Solution test = new Solution();
List<List<Integer>> lists = test.threeSum(new int[]{-1, 0, 1, 2, -1, -4});
System.out.println(lists);
}
}