链接:https://leetcode-cn.com/problems/two-sum/
中文题目:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
英文题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution, and you may not use the same element twice.
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思路:
使用哈希表来存储所需的因子,遍历数组,先前若存在该数的因子则作为答案返回,若不存在,则将此数作为因子存入哈希表。
题解:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> require = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
// 因子已经在前面出现过
if (require.containsKey(target - nums[i])) {
result[0] = require.get(target - nums[i]);
result[1] = i;
return result;
}
// 将这个数作为因子存入hash表中
require.put(nums[i], i);
}
return result;
}
}