C++刷题笔记:哈希表 map

文章目录


两数之和

利用map容器“一对一”记录两数关系. 主要思路是查找对偶数other是否被记录, 如果无,则将当前元素作为对偶数存入map;如果存在对偶数,则返回二者的索引. 时间复杂度 O ( n ) O(n) O(n), 空间复杂度 O ( n ) O(n) O(n)

class Solution 
{
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        map<int, int> record;
        for(int i=0; i<nums.size(); i++)
        {
            int other = target - nums[i];
            if(record.count(other))
            {
                return {i, record[other]};
            }
            else
            {
                other = nums[i];
                record[other] = i;
            }
        }
        return {-1,-1};
    }
};

全部评论

相关推荐

八极星:有什么不能问的,(/_\),这又不是多珍贵的机会,你有什么可失去的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务