题意
给定一个数组和一个目标值,找出数组中和为目标值的两个数的下标。
思路
直接暴力利用哈希表键值一一对应的特点:将数组的值和下标存入哈希表,仅需一趟遍历,使用hashMap.containsKey即可根据自己的键找出另一半的值是否包含在数组中。
代码
class solution{
public int [] twoSum(int[] nums, int target){
int len = nums.length;
HashMap<Integer, Integer> hashMap = new HashMap<>(len - 1);
hashMap.put(nums[0], 0);
for(int i = 0; i < len; i++){
int another = target - nums[i];
if(hashMap.containsKey(another)){
return new int[]{
i, hashMap.get(another)};
}
hashMap.put(nums[i], i);
}
throw new IllegalArgumentException("no answer!");
}
}