【题解】1. 两数之和 (数组、哈希表)

https://leetcode.cn/problems/two-sum/?envType=study-plan-v2&envId=top-100-liked
在这里插入图片描述

查找表法:

  • 在遍历的同时,记录一些信息,以省去一层循环,这是“以空间换时间”的想法
  • 需要记录已经遍历过的数值和它对应的下标,可以借助查找表实现
  • 查找表有两个常用的实现:
  • 哈希表
  • 平衡二叉搜索树
class Solution {
    
    
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    
    
        // 创建一个哈希表用于存储每个数字及其索引
        unordered_map<int, int> countMap;
        int n = nums.size(); // 获取数组的大小
        
        // 遍历数组中的每个元素
        for (int i = 0; i < n; ++i)
        {
    
    
            // 查找是否存在一个数字,其与当前数字的和等于目标值
            auto it = countMap.find(target - nums[i]);
            if (it != countMap.end()) 
            {
    
    
                // 如果找到,返回这两个数字的索引
                return {
    
    it->second, i};
            }
            // 如果未找到,将当前数字及其索引存入哈希表
            countMap[nums[i]] = i; 
        }
        
        // 如果没有找到符合条件的两个数,返回空向量
        return {
    
    };
    }
};

猜你喜欢

转载自blog.csdn.net/Colorful___/article/details/141123472