题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思路
java实现,HashMap键不能重复,遍历数组将值加入到HashMap中,键为数组值,值为索引,并引入判断,如果HashMap中存在(target - nums[i])的键,则说明找到了。
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> ma = new HashMap();
for (int i = 0; i < nums.length; ++i) {
if (ma.containsKey(target - nums[i])) {
return new int[] {ma.get(target - nums[i]), i};
} else {
ma.put(nums[i], i);
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
思路
C++实现,用C++标准库中的无序字典 unordered_map 。
- 定义一个 unordered_map 容器 record 用来记录元素的键与值,定义一个 vector 用来返回结果,然后以 i 为索引遍历数组 nums。
- 每次遍历时使用临时变量 goal 用来保存 target 与当前值 nums[i] 的差值。
- 在此次遍历中查找 record 中是否有与 goal 一致的键,如果查找成功则将查找到的键的值 record[goal] 压入 vec 中,再将 nums 中当前值的索引 i 压入 vec 中。
- 如果未找到,则在 record 中保存一个键值对,键为 nums[i] ,值为 i 。
注:map 中的 find 函数返回迭代器,如果找到指向被查找元素的位置,如果找不到,指向 map.end()
代码
class Solution{
public:
vector<int> twoSum(vector<int> &nums, int target){
unordered_map<int, int> record;
vector<int> vec;
int i;
for(i = 0; i < nums.size(); i++){
int goal = target - nums[i];
if(record.find(goal) != record.end()){
vec.push_back(record[goal]);
vec.push_back(i);
}
else
record[nums[i]] = i;
}
return vec;
}
};