上一篇的解法容易理解,采用了暴力求解法,但是时间复杂度是O(n^2),
这里,采用了HashMap的方法,时间复杂度是O(n),实际上就是通过HashMap去掉了一层for循环,通过空间换时间,空间复杂度为O(n)
可以参考我的上一篇文章,对照阅读 两数之和 两层for循环版
package SumOfTwoNum;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Solution2 {
public static int[] hashFindTwoNum(int[] nums, int target) {
int len = nums.length;
//因为这里的最大长度为len-1
//在这个map中,key表示具体的数,value表示标
Map<Integer, Integer> map = new HashMap<Integer, Integer>(len - 1);
for(int i = 0; i < len; i ++) {
if(map.containsKey(target - nums[i])) {
return new int[] {i, map.get(target - nums[i])};
}
//第一步就执行了
map.put(nums[i], i);
}
throw new IllegalArgumentException("没有找到");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入数组:(以逗号分隔开)");
//获得输入的数组
String str = sc.nextLine();
//拆分
String[] strs = str.split(",");
int[] nums = new int[strs.length];
//转化
for(int i = 0; i < strs.length; i ++) {
nums[i] = Integer.parseInt(strs[i]);
}
System.out.println("请输入目标数");
int target = sc.nextInt();
int[] solution = hashFindTwoNum(nums, target);
System.out.println("找到的解为:" + "下标" + (solution[1] + 1) + "\t" + "下标" + (solution[0] + 1));
}
}
运行截图
请输入数组:(以逗号分隔开)
2,35,4,6,15,23,88,41,25,
请输入目标数
19
找到的解为:下标3 下标5