欧克吖~
我是悟 空,经历了前一个月各种面试,在算法方面被 “算法题按在地上打、摩擦~”。
决定细心革面重新刷题:开启LeetCode模式:备战秋招了!
我会把自己刷题的代码放在这里做参考。
如果对你有用的话,可以关注我的更新,大家一起成长!
送给大家:"王也道长"的一句话:
Java刷题Tips:多多运用集合类来解题!
关于题解思路大家可以直接看Leetcode的题解,非常的清晰:
这里有到两种方法
- 直接暴力题解:两层for循环(乌拉乌拉就完事儿了)
- Map类的运用:分为两种
- 进行预处理的(先把数组放进Map,在比较)
- 直接比较(先比较,再放进Map数组)快!
只写题解:
public class _1TwoSum {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 74, 5, 6};
// System.out.println(Arrays.toString(TwoSum(arr, 10)));
// System.out.println(Arrays.toString(TwoSumMap(arr, 8)));
System.out.println(Arrays.toString(TwoSumMapTwo(arr, 8)));
}
//1.暴力求解 时间复杂度 n^2;
// 空间复杂度 1
public static int[] TwoSum(int[] arr, int target) {
// 注意边界
if (arr == null || arr.length == 0) {
return new int[0];
}
for (int i = 0; i < arr.length - 1; i++) {
//i+1 保证两次不重复
for (int j = i + 1; j < arr.length - 1; j++) {
if (arr[i] + arr[j] == target) {
return new int[]{i, j};
}
}
}
return null;
}
// 2.map 优化查找: 时间复杂度 2n 两次 for 循环:
// 空间复杂度 n
public static int[] TwoSumMap(int[] arr, int target) {
if (arr == null || arr.length == 0) {
return new int[0];
}
// map 进行预处理
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length - 1; i++) {
map.put(arr[i], i);
}
for (int j = 0; j < arr.length - 1; j++) {
int x = arr[j];
// 这里是吧 key = arr[j]的值,value =下标!
if (map.containsKey(target - x)) {
int index = map.get(target - x);
// 因为做了预处理,map里面有了一份元素, 要保证key 不能重合 即 hash的key值不能相同;
if (index != j) return new int[]{j, index};
}
}
return null;
}
// 3.map 优化查找: 时间复杂度 n 一次 for 循环:
// 空间复杂度 n
public static int[] TwoSumMapTwo(int[] arr, int target) {
if (arr == null || arr.length == 0) {
return new int[0];
}
// map 进行预处理
Map<Integer, Integer> map = new HashMap<>();
for (int j = 0; j < arr.length - 1; j++) {
int x = arr[j];
if (map.containsKey(target - x)) {
// index 是map的value 值! 存的是 下标!
int index = map.get(target - x);
// 保证key 不能重合 即 hash的key值不能相同;
// if (index != j) 不会重复: 因为是没做预处理,先进行判断,后put的 key 不会重复
return new int[]{j, index};
}
// 这里是吧 key = arr[j]的值,value =下标!
map.put(x,j);
}
return null;
}
}
关于算法的学习:
两个重要关键名词:
- 时间复杂度:
- 空间复杂度:
具体的理解可以看这篇文章:
图解时间复杂度