题意
给定一个数组和一个目标值,找出数组中和为目标值的两个数的下标。
思路
直接暴力利用哈希表键值一一对应的特点:将数组的值和下标存入哈希表,仅需一趟遍历,使用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!");
}
}
本文介绍了一种高效的解决方案来解决经典的两数之和问题。通过使用哈希表存储数组元素及其对应的索引,可以在O(n)的时间复杂度内找到和为目标值的两个数的索引。
3393

被折叠的 条评论
为什么被折叠?



