暴力for:
class Solution { public: vectortwoSum(vector & nums, int target) { for(int i = 0;i < nums.size();i++){ for(int j = i + 1;j < nums.size();j++){ if(nums[i]+nums[j]==target){ return{i,j}; } } } return {}; } };
哈希:
class Solution { public: vectortwoSum(vector & nums, int target) { unordered_map hash_map; for(int i = 0;i < nums.size();i++){ auto it = hash_map.find(target - nums[i]); if(it != hash_map.end()){ return {it->second,i}; } hash_map[nums[i]] = i; } return {}; } };
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)