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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
题目描述:
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数的索引。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
思路分析:
为了找到两个数索引,可以固定一个nums[i],然后再在数组中搜索(target-nums[i])的索引。
1. 暴力破解
两层遍历,固定一个元素,循环搜索另外一个元素,时间复杂度0(n^2),效率太低舍弃;
2. Hash map
由于对Hash表的搜索是0(1),所以我们可以先把数组元素全部放入Hash表(因为要求返回元素索引,所以让数组元素作键,数组元素索引作值)。这样只需一遍遍历数组元素即可,时间复杂度0(n)。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> vi;
unordered_map<int,int> hmap;//声明一个hash map表
for(auto i = 0; i < nums.size(); i++){
hmap.insert(pair<int,int>(nums[i],i));
}
for(auto j = 0; j < nums.size(); j++){
if(hmap.find(target - nums[j]) != hmap.end()){
int k = hmap[target - nums[j]];
if(k < j){
vi.push_back(k);
vi.push_back(j);
}
}
}
return vi;
}
};
参考