0%

LeetCode-18

题目

结果

代码

四重循环之再去重

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new LinkedList<>();
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
for (int k = j + 1; k < nums.length; k++) {
for (int l = k + 1; l < nums.length; l++) {
if (nums[i] + nums[j] + nums[k] + nums[l] == target) {
// 不直接add(List.of(x,x,x))是因为List.of生成的list不能修改
ans.add(new LinkedList<>(List.of(nums[i], nums[j], nums[k], nums[l])));
}
}
}
}
}
// 排序以便去重
ans.forEach(list -> list.sort(Integer::compareTo));
// 去重并返回
return ans.stream().distinct().collect(Collectors.toList());
}
}

复杂度

时间复杂度:O(n^4)

空间复杂度:O(1)