两数之和
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
分析
遍历一遍数组,对每个元素nums[1],查询是否存在target - nums[1]
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map= new HashMap<Integer,Integer>();
int[] result = new int[2];
for(int i =0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
result[0] = i;
result[1] = map.get(target - nums[i]);
break;
}
map.put(nums[i],i);
}
return result;
}
}

本文介绍了一种解决“两数之和”问题的有效算法。该算法通过一次遍历数组并使用哈希表来快速查找目标值减当前元素后的差值是否存在于数组中,从而找到两个数的下标。这种方法大大提高了查找效率。
161

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



