Title
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].
Solution
这个还有待改进,但现有知识不足,留以后改进
//cpp:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i=0;i<nums.size();i++){
for(int j=i+1;j<nums.size();j++){
if(nums[i]+nums[j]==target){
vector<int> res;
res.push_back(i);
res.push_back(j);
return res;
}
}
}
}
};
补充,第一种方法用hash表,用一个map记录元素值和对应的位置
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> umap;
for (int i = 0; i < nums.size(); i++) {
umap[nums[i]] = i;
}
for (int i = 0; i < nums.size(); i++) {
int t = target - nums[i];
if (umap.find(t) != umap.end()&&umap.at(t)!=i) {
vector<int> v;
v.push_back(i);
v.push_back(umap[t]);
return v;
}
}
}
};
可以再优化下,两个值的和为一个值,因此,肯定可以在第二个数字的前面找到第一个数字的!!!
就是每次umap.find…然后再Put当前的