学习资源:拉勾教育
问题定位和技术选型
示例:在一个包含n个元素的无序数组a中,输出其最大值max_val
- 该问题属于查找问题,考虑用O(logn)的二分查找,但因为数组无序,导致它不适用
- 因为必须把全部数据过一遍,因此考虑用O(n)的检索方法,这就是复杂度的下限
public class Main {
public static void s1_3() {
int a[] = { 1, 4, 3 };
int max_val = -1; // 记录最大值
int max_inx = -1; // 记录最大值的下标
for (int i = 0; i < a.length ; i++) {
if (a[i] > max_val) {
max_val = a[i];
max_inx = i;
}
}
System.out.println(max_val);
}
public static void main(String[] args) {
s1_3();
}
}
通用解题的方法论
- 复杂度分析——估算问题中复杂度的上限和下限
- 定位问题——根据问题类型,确定采用何种算法思维
- 数据操作分析——根据增、删、查和数据顺序关系去选择合适的数据结构,利用空间换取时间
- 编码实现
案例1——找到出现次数最多的那个数字
在一个数组a=[1,3,4,3,4,1,3],找到出现次数最多的那个数字,如果并列存在多个,随机输出一个
- 预期的时间复杂度是
O(n)
,这就意味着编码采用一层的for循环,对原数组进行遍历 - 数据结构需要额外设计哈希表,其中key是数组的元素,value是频次,这样可以支持
O(1)
时间复杂度的查找操作
import java.util.*;
public class Main {
public static void s2_4() {
int a[] = { 1, 3, 4, 3, 4, 1, 3, 1 };
Map<Integer, Integer> d = new HashMap<>();
for (int i = 0; i < a.length; i++) {
if (d.containsKey(a[i])) {
d.put(a[i], d.get(a[i]) + 1);
} else {
d.put(a[i], 1);
}
}
int val_max = -1;
int time_max = 0;
for (Integer key : d.keySet()) {
if (d.get(key) > time_max) {
time_max = d.get(key);
val_max = key;
}
}
System.out.println(val_max);
}
public static void main(String[] args) {
s2_4();
}
}
案例2——找出加和等于目标值的两个整数
给定一个整数数组arr和一个目标值target,请你在该数组中找出加和等于目标值的两个整数,并返回它们在原数组中的下标
- 预期的时间复杂度是
O(n)
,这就意味着编码采用一层的for循环,对原数组进行遍历 - 数据结构需要额外设计哈希表,其中key是
target-arr[i]
,value是index,这样可以支持O(1)
时间复杂度的查找操作
import java.util.*;
public class Main {
private static int[] twoSum(int[] arr, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length ; i++) {
map.put(arr[i], i);
}
for (int i = 0; i < arr.length ; i++) {
int complement = target - arr[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { map.get(complement), i };
}
}
return null;
}
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6};
int[] result = twoSum(arr, 10);
for(int i = 0 ; i < result.length ; i++) {
System.out.print(result[i] + " ");
}
}
}