1 vector<int> twoSum(vector<int> &numbers, int target) 2 { 3 //Key is the number and value is its index in the vector. 4 unordered_map<int, int> hash; //unordered_map是无序关联容器 5 vector<int> result; 6 for (int i = 0; i < numbers.size(); i++) { 7 int numberToFind = target - numbers[i]; 8 9 //if numberToFind is found in map, return them 10 if (hash.find(numberToFind) != hash.end()) { //find()返回一个迭代器,指向区间[first,last](hash的序号)中第一个值为value的元素,如果没有找到就返回last 11 //+1 because indices are NOT zero based 12 result.push_back(hash[numberToFind] + 1);//push_back(t)将t插到a.end()前面 13 result.push_back(i + 1); 14 return result; 15 } 16 17 //number was not found. Put it in the map. 18 hash[numbers[i]] = i; 19 } 20 return result; 21 }
无序关联容器有:unordered_set unordered_multiset unordered_map unordered_multimap,它们使用键和哈希表,以便能够快速存取数据。没有了有序关联容器的lower_bound 和upper_bound,所比较基于等于概念。
时间: 2024-10-11 10:43:06