C++unordered_map使用例子

来源:互联网 发布:js延迟一秒 编辑:程序博客网 时间:2024/06/16 08:02

1.

#include<tr1/unordered_map>using namespace std;class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> result(2, -1);        typedef unordered_map<int, int> Hhashmap;        typedef Hhashmap::value_type hmType;        typedef Hhashmap::iterator hmIter;        Hhashmap hashmap;        for (int x=0; x< nums.size(); x++){            hashmap.insert(hmType(nums[x],x));        }        for (int j=0; j< nums.size(); j++){            for(hmIter iter=hashmap.begin();iter!=hashmap.end();++iter){                if(iter->first == (target - nums[j]) && j != iter->second){                    result[0] = j;                    result[1] = iter->second;                }            }        }        return result;    }};

2.

#include<tr1/unordered_map>using namespace std;class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> result(2, -1);        typedef unordered_map<int, int> Hhashmap;        typedef Hhashmap::value_type hmType;        typedef Hhashmap::iterator hmIter;        Hhashmap hashmap;        for (int x=0; x< nums.size(); x++){            for(hmIter iter=hashmap.begin();iter!=hashmap.end();++iter){                if(iter->first == (target - nums[x]) && x != iter->second){                    result[0] = x;                    result[1] = iter->second;                    return result;                }            }                        hashmap.insert(hmType(nums[x],x));        }        return result;    }};
原创粉丝点击