欧克吖~
我是悟 空,经历了前一个月各种面试,在算法方面被 “算法题按在地上打、摩擦~”。
决定细心革面重新刷题:开启LeetCode模式:备战秋招了!
我会把自己刷题的代码放在这里做参考。
如果对你有用的话,可以关注我的更新,大家一起成长!
今天是 167. 三数之和。 属于 两数之和的变形。
送给大家:"王也道长"的一句话:
15三数之和
具体的解题思路:总结了三种思路:
public class _15ThreeSum {
public static void main(String[] args) {
int[] arr = {-1, 0, 1, 2, -1, 4};
System.out.println(ThreeSumThree(arr).toString());
System.out.println(ThreeSumTwo(arr).toString());
}
//1.暴力解决: 直接三层for循环 时间复杂度: n^3+n
// 空间复杂度 n
// 题目核心:保证 “三数之和的值不能重复!”
public static List<List<Integer>> ThreeSum(int[] arr) {
if (arr == null || arr.length < 3) return null;
Set<List<Integer>> set = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
for (int k = j + 1; k < arr.length; k++) {
if (arr[i] + arr[j] + arr[k] == 0) {
// 启用临时的变量组 temp 来保管所有的 符合三数之和的值: 但是(会有重复值!)
List<Integer> temp = Arrays.asList(arr[i], arr[j], arr[k]);
// 进行排序 保证 各个list的数组位置相同!
Collections.sort(temp);
// 利用set 去重!
set.add(temp);
}
}
}
}
// 重新转为 题目要求的ArrayList<integer>
return new ArrayList<>(set);
}
//2.优化: 二分查找: 时间复杂度: n^2
// 二分查找的前提: 有序是前提:
public static List<List<Integer>> ThreeSumTwo(int[] arr) {
Arrays.sort(arr);
Set<List<Integer>> set = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
// 这里就把三数之和 转换程2数 之和。 变成了 i 和 -i 的问题:
int target = -arr[i];
// 双指针问题:
int left = i + 1;
int right = arr.length - 1;
while (left < right) {
// 注意指针走向问题:
if (target > (arr[left] + arr[right])) {
left++;
} else if (target < (arr[left] + arr[right])) {
right--;
} else {
set.add(Arrays.asList(arr[i], arr[left], arr[right]));
// 这里很关键。因为不知道是否只有一组,所以 找到后 继续跳过当前值前进。
left++;
right--;
}
}
}
return new ArrayList<>(set);
// 这里还这里优化: 因为转换为ArrayList<>(set); 也用了 n 的时间复杂度。
}
public static List<List<Integer>> ThreeSumThree(int[] arr) {
Arrays.sort(arr);
List<List<Integer>> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
//优化第三步: 保证当前 i的数和前面一个不同。
if (i > 0 && arr[i] == arr[i - 1]) continue;
// 这里就把三数之和 转换程2数 之和。 变成了 i 和 -i 的问题:
int target = -arr[i];
// 双指针问题:
int left = i + 1;
int right = arr.length - 1;
while (left < right) {
// 注意指针走向问题:
if (target > (arr[left] + arr[right])) {
left++;
} else if (target < (arr[left] + arr[right])) {
right--;
} else {
list.add(Arrays.asList(arr[i], arr[left], arr[right]));
// 去重的优化: 保证左右两边的指针的下一位 一直往后走都不能重复。
while (left < right && arr[left] == arr[++left]) ;
while (left < right && arr[right] == arr[--right]) ;
}
}
}
return list;
// 这里优化: 因为转换为ArrayList<>(set); 也用了 n 的时间复杂度。
// 直接:有了list 省了一次 时间复杂度 n的转换。
}
}