// 定义一个名为 Solution 的类 class Solution { public: // 定义一个名为 twoSum 的公有函数,该函数接受一个整型数组和一个整型变量作为参数,并返回一个整型数组 vector twoSum(vector& nums, int target) { // 定义一个名为 hashtable 的无序 map,用于存储数组中的数值和它们对应的下标 unordered_map<int, int> hashtable; // 遍历整型数组 nums for (int i = 0; i < nums.size(); ++i) { // 在 hashtable 中查找 target - nums[i] 是否存在 auto it = hashtable.find(target - nums[i]); // 如果存在,返回该数值的下标和当前数值的下标 if (it != hashtable.end()) { return {it->second, i}; } // 在 hashtable 中存储当前数值及其下标 hashtable[nums[i]] = i; } // 如果找不到符合要求的数值,则返回一个空数组 return {}; } }

对下面代码逐一注释:class Solution public vectorint twoSumvectorint& nums int target unordered_mapint int hashtable; for int i = 0; i numssize; ++i auto it = hashtablefindtarget -

原文地址: http://www.cveoy.top/t/topic/fmlN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录