1.Two Sum
leetcode第一题
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].
思路很简单,可以用一个词典来存储当前数字A的位置和与当前数字A相加等于target的数,然后判断下一个数字B是否在词典中,如果在,则返回A和B的位置,如果不在就将B加入词典。
以下是c++代码:
class Solution{
public:
vector<int> twoSum(vector<int>& nums,int target){
map<int,int> hash;
vector<int> result;
for(int i =0;i<nums.size();i++){
int numToFind =target-nums[i];
#cout<<hash.end()<<endl;
if (hash.find(numToFind)!=hash.end()){
result.push_back(hash[numToFind]);
result.push_back(i);
return result;
}
hash[nums[i]]=i;
}
return result;
}
};
第一次使用C++做OJ,vector是c++的容器,大小可以变化,可以向其中增加元素。map也是一种容器相当于python中的词典,其中存着key-value对,可以根据key迅速查找。
vector的常用操作有:
1. v.push_back(t) 在容器的最后加入一个值为t的数据,容器的size变大。另外list有push_front()函数,在前端插入,后面的元素下标依次增大。
2. v.size() 返回容器中数据的个数,size返回对应vector类定义的size_type的值。v.resize(2*v.size)或v.resize(2*v.size, 99) 将v的容量翻倍(并把新元素的值初始化为99)
3. v.empty() 推断vector是否为空
4. v[n] 返回v中位置为n的元素
5. v.insert(pointer,number, content) 向v中pointer指向的位置插入number个content的内容。
6. v.pop_back() 删除容器的末元素,并不返回该元素。
7.v.erase(pointer1,pointer2) 删除pointer1到pointer2中间(包含pointer1所指)的元素。
8. v1==v2 推断v1与v2是否相等。
9. p=v1.end( ); p指向v1的最后一个元素的下一位置。
10.v.clear()
map的常用操作有: https://blog.csdn.net/sevenjoin/article/details/81943864
在查找操作时map.find(num)->second为value,map.find(num)->first为key