leetcode268. Missing Number

文章目录

一、题目

Given an array nums containing n distinct numbers in the range 0, n, return the only number in the range that is missing from the array.

Example 1:

Input: nums = 3,0,1

Output: 2

Explanation: n = 3 since there are 3 numbers, so all numbers are in the range 0,3. 2 is the missing number in the range since it does not appear in nums.

Example 2:

Input: nums = 0,1

Output: 2

Explanation: n = 2 since there are 2 numbers, so all numbers are in the range 0,2. 2 is the missing number in the range since it does not appear in nums.

Example 3:

Input: nums = 9,6,4,2,3,5,7,0,1

Output: 8

Explanation: n = 9 since there are 9 numbers, so all numbers are in the range 0,9. 8 is the missing number in the range since it does not appear in nums.

Constraints:

n == nums.length

1 <= n <= 104

0 <= numsi <= n

All the numbers of nums are unique.

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

二、题解

使用哈希表的方法解决

cpp 复制代码
class Solution {
public:
    int missingNumber(vector<int>& nums) {
        unordered_map<int,int> map;
        int n = nums.size();
        for(int i = 0;i < n;i++) map[nums[i]] = 1;
        for(int i = 0;i <= n;i++){
            if(!map.count(i)) return i;
        }
        return 0;
    }
};
相关推荐
专注仿真1 小时前
问答大模型技术方案算法实现-熵权法融合算法 + 交叉编码器重排算法
人工智能·python·算法·语言模型·问答大模型关键算法·熵权融合算法·交叉编码器重排算法
烧酒同学2 小时前
【C++】记录size of std::vector的巧妙坑
开发语言·c++·图形渲染
地平线开发者2 小时前
量化为什么会有损失:从量化误差到精度下降
算法
手写码匠3 小时前
华为云Flexus+DeepSeek征文|Dify 多 Agent 会话管理与上下文工程实战:让智能体“记住该记住的,忘掉该忘掉的“
人工智能·深度学习·算法·aigc
2401_862880823 小时前
数据结构 --- 栈
c语言·数据结构·算法
致Great3 小时前
Qwen3.8-27B 接入 DSH 全流程实测:写代码、跑长任务,都没问题
算法
Tisfy4 小时前
LeetCode 3471.找出最大的几近缺失整数:三种情况判断
算法·leetcode·题解·分类讨论
linux-hzh4 小时前
百日算法修炼 · Day 12
算法·深度优先
@呱呱爱学习4 小时前
C++大成之路_ STL容器_ Vector
开发语言·c++
额额额对了4 小时前
数据结构:二叉树
c语言·数据结构·算法