leetcode-1.Two Sum
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].
- 解法1
vector::push_back—Add element at the end
把新的元素加在最后
vector::pop_back—Delete last element (public member function)
把最后的元素删除
vector::insert—Insert elements (public member function)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
for(int i=0; i < nums.size(); ++i){
for(int j = i+1; j < nums.size(); ++j){
if(nums[i]+nums[j]==target){
res.push_back(i);
res.push_back(j);
}
}
}
return res;
}
};
2.解法2
用了map这种数据结构,一开始先把数据存进去
第二次看在map中有没有能与这个元素配对的
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
map<int, int> m;
for(int i=0; i < nums.size(); ++i){
m[nums[i]]=i; //注意!!
}
for(int i=0; i < nums.size(); ++i){
int t = target - nums[i];
if(m.count(t) && m[t] != i){ // &&后面的,题目说每一个数字不能用两次
res.push_back(i); //分清()[]
res.push_back(m[t]);
break; //刚开始忘了break
}
}
return res;
}
};
unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value。不同的是unordered_map不会根据key的大小进行排序,存储时是根据key的hash值判断元素是否相同,即unordered_map内部元素是无序的,而map中的元素是按照二叉搜索树存储,进行中序遍历会得到有序遍历。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;//unordered_map 元素之间没有大小关系
for(int i=0; i < nums.size(); ++i){
m[nums[i]]=i;
}
for(int i=0; i < nums.size(); ++i){
if(m.count(target - nums[i]) && m[target - nums[i]] != i){
return {i, m[target - nums[i]]}; //这里return的就是一个map
}
}
}
};
a = 0;
i = 1;
a += (i++); a = 2;
a += (++i); a = 1;
在这里(++i)/(i++)是不一样的
for(a;b;c)
a
b
body
c;
b
body
在for循环中(++i)/(i++)是一样的