题目简介(简单)
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
题目思路
1.暴力求解法。时间复杂度O(n2)
2.哈希表法。时间复杂度O(n)
2.1利用哈希表的一个方法:hashmap.containsKey()。不用依次遍历数组中是否存在这个值,降低了复杂度。
2.2思路分析
建立hashmap(key为数值,value为下标),判断hashmap中是否存在target-nums[i],如果存在返回该下标值与i。不存在则将该值加入到hashmap中。
具体程序
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (hashMap.containsKey(target - nums[i])){
int value = hashMap.get(target- nums[i]);
return new int[]{value,i};
}else {
hashMap.put(nums[i],i);
}
}
throw new IllegalArgumentException("No answer");
}
}