题目:
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].
题意:
给出一个数组和一个目标数,在数组中找出两个元素的和为目标数,求这两个元素的下标。ps:只有一对元素且下标从小到大输出。
思路:
第一反应是hash表查找,利用STL中的map容器标记数组中的元素,另其为数组元素下标+1(因为map容器初始值为0,数组元素下标从0开始)。然后就是遍历整个数组元素,查找与当前元素和为目标数的另一个元素是否存在。若存在,则将两个元素的下标放入vector中~当然还有别的方法,比如先排序后二分查找等,比较懒就不写了~
Code:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int>q;
int i,key,len=nums.size();
q[nums[0]]=1;
for(i=1;i<len;i++){
key=target-nums[i];
if(q[key]!=0){
vector<int> result;
result.push_back(q[key]-1);
result.push_back(i);
return result;
}
q[nums[i]]=i+1;
}
}
};