题目:两数之和
想当然的,法一:暴力破解
public static int[] getIndexs(int[] arr, int target){
int[] indexs = new int[2];
for (int i = 0; i < arr.length-1; i++){
//因为是两个数相加,第一次循环没必要循环到最后一个数,到倒数第二个就行了,所以是 length-1
for (int j = i+1; j < arr.length; j++){
//不能重复的两个数相加,所以 j 从i+1 开始
if (arr[i] + arr[j] == target){
indexs[0] = i;
indexs[1] = j;
}else {
//如果在数组里找不到和为 target 的两个数,就返回[-1,-1]
return new int[]{-1,-1};
//不写这个的话,下面要抛出异常才行
}
}
}
// throw new IllegalArgumentException("没有这样的两个数!");
return indexs;
}
显然,暴力破解的话,
时间复杂度:O(n^2)
空间复杂度:O(1)
时间复杂度相比空间复杂度来说太大了,所以考虑用空间换时间
法二:用HashMap
在暴力破解中,第一层循环和第二层循环是有重复的数的,而HashMap可以防止重复
public static int[] getIndexs2(int[] arr, int target){
int[] indexs = {-1,-1};
int length = arr.length;
//最好给 HashMap 指定初始长度,因为题目给定说会有解,所以这里长度可以写 length-1
HashMap<Integer, Integer> map = new HashMap<>(length - 1);
//HashMap 刚开始肯定没有数据
map.put(arr[0], 0);
for (int i = 1; i < length; i++){
int temp = target - arr[i];
if (map.containsKey(temp)){
//如果在哈希表里
indexs[0] = map.get(temp);
indexs[1] = i;
}else {
//不在表里
map.put(arr[i], i);
}
}
return indexs;
// throw new IllegalArgumentException("找不到这样的两个数!");
}
有关使用哈希表解决这道题的写法,官方题解的视频里很清楚
提交记录: