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 <= nums[i] <= 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;
    }
};
相关推荐
源代码•宸21 分钟前
分布式缓存-GO(分布式算法之一致性哈希、缓存对外服务化)
开发语言·经验分享·分布式·后端·算法·缓存·golang
旖旎夜光1 小时前
多态(11)(下)
c++·学习
yongui478341 小时前
MATLAB的指纹识别系统实现
算法
高山上有一只小老虎1 小时前
翻之矩阵中的行
java·算法
yangpipi-1 小时前
《C++并发编程实战》 第4章 并发操作的同步
开发语言·c++
jghhh011 小时前
RINEX文件进行卫星导航解算
算法
Chance_to_win1 小时前
C++基础知识
c++
爱思德学术1 小时前
中国计算机学会(CCF)推荐学术会议-A(计算机科学理论):LICS 2026
算法·计算机理论·计算机逻辑
CVHub2 小时前
多模态图文训推一体化平台 X-AnyLabeling 3.0 版本正式发布!首次支持远程模型推理服务,并新增 Qwen3-VL 等多款主流模型及诸多功能特性,等
算法
有趣的我2 小时前
C++ 多态介绍
开发语言·c++