题目:两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解法一:求任意两数和,若得到与target相同的数值,则返回下标。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] index = new int[2];
for(int i = 0; i < nums.length ;i++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
index[0] = i;
index[1] = j;
}
}
}
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length ; i++){
if(hash.containsKey(nums[i])){
index[0] = hash.get(nums[i]);
index[1] = i;
}
hash.put(target-nums[i],i);
}
return index;
}
}
运行结果:
解法二:使用HashMap求补数
首先,第一轮循环将第一个数值的补数及该数值的下标存入hashmap,再遍历nums查找是否存在补数,若存在则将该数值下标及其补数下标存入index数组。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] index = new int[2];
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length ; i++){
if(hash.containsKey(nums[i])){
index[0] = hash.get(nums[i]);
index[1] = i;
}
hash.put(target-nums[i],i);
}
return index;
}
}
运行结果:
由此可知,使用哈希表的查找效率更高,速度更快。