题解 | #两数之和#
两数之和
https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
import java.util.*;
//get方法,通过key找value
//通过value找key很复杂,因此让数组值作为key,数组索引作为value
//注意考虑各种情况,返回结果应该是什么形式
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] numbers, int target) {
// write code here
// 问题是:简单的方法,时间复杂度过高
// 使用hashMap,为我们自动匹配值,不需要再遍历匹配
HashMap<Integer,Integer> hm = new HashMap<>();
// 依次将数组中的值写入hashmap,同时匹配值,减少时间复杂度
for(int i=0;i<numbers.length;i++){
int tag = target - numbers[i];//需要匹配的值
if(!hm.containsKey(tag)){//hashmap不存在,则将元素加入
hm.put(numbers[i],i);
}else{//存在,直接返回
return new int[]{hm.get(tag)+1,i+1};//存在,说明当前位置更大
}
}
return new int[0];//没有则返回空数组
}
}

查看10道真题和解析