[Array]1. Two Sum(map和unorder_map)

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].

思路:对于这种的不能进行排序,排序之后的元素下标就变的不一样了。

自己的代码:还是很低级,之前做过167了。。。。遍历实在浪费时间
vector<int> twoSum(vector<int>& nums, int target) {
       vector<int>index;
        int n = nums.size();
        for(int i = 0; i < n-1; i++){
            for(int j = i+1; j < n; j++){
                if(nums[i] + nums[j] == target){
                    index.push_back(i);
                    index.push_back(j);
                     //return vector<int>{i,j};
                }
            }
        }
        return index;
}

优秀代码:

vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int>temp;
for(int i = 0; i < nums.size(); i++){
int sub = target = nums[i];
if(temp.find(sub) != nums.end()){
return vector<int>{temp[sub], i};
else
temp[nums[i]] = i; //这里将元素值和元素下标对应
}
}
}
     

unordered_map用法

[查找元素是否存在]

 find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。
    若有unordered_map<int, int> mp;查找x是否在map中
    方法1:  若存在  mp.find(x)!=mp.end()
    方法2:  若存在  mp.count(x)!=0

[插入数据]
    map.insert(Map::value_type(1,"Raoul"));
[遍历map]
    unordered_map<key,T>::iterator it;
    (*it).first;        //the key value
    (*it).second   //the mapped value
    for(unordered_map<key,T>::iterator iter=mp.begin();iter!=mp.end();iter++)
          cout<<"key value is"<<iter->first<<" the mapped value is "<< iter->second;

map用法

map经常用于c++中的二维数组,虽然我以前一直用vector<int, vector<int> >,还是要学着用一下map

参考:http://blog.csdn.net/u012530451/article/details/53228098; http://blog.csdn.net/bzhxuexi/article/details/24182087

原文地址:https://www.cnblogs.com/qinguoyi/p/7350772.html