学习使用标准模板库(STL)中的map,hash_map。涉及数据结构知识:哈希表,红黑树。
map的使用方法
https://www.cnblogs.com/fnlingnzb-learner/p/5833051.html
hash_map的原理和使用方法
https://blog.csdn.net/ddkxddkx/article/details/6555754
两遍哈希表
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> index(2); int num = nums.size(); map<int, int> nums_map; for (int i = 0; i < num; i++) { nums_map[nums[i]] = i; } map<int, int>::iterator iter; // 查看是否存在相同“键”而覆盖的情况 for (iter = nums_map.begin(); iter != nums_map.end(); iter++) { cout << iter->first <<" " << iter->second<<endl; } num = nums_map.size(); for(int j=0; j<num; j++){ int complement = target - nums[j]; if (nums_map.count(complement) && nums_map.find(complement)->second != j){ index = {j, nums_map.find(complement)->second}; return index; } } return index; } };
一遍哈希表
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> index(2); int num = nums.size(); map<int, int> nums_map; int complement; for (int i = 0; i<num; i++) { // nums_map[nums[i]] = i; 若放在这里,当出现nums = [3,3], tareget = 6时会出现报错 complement = target - nums[i]; if (nums_map.count(complement) && nums_map.find(complement)->second != i) { index ={i, nums_map.find(complement)->second}; return index; } nums_map[nums[i]] = i; } map<int, int>::iterator iter; // 查看是否存在相同“键”而覆盖的情况 for (iter = nums_map.begin(); iter != nums_map.end(); iter++) { cout << iter->first <<" " << iter->second<<endl; } return index; } };
最新评论