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;
    }
};
相关推荐
whoarethenext6 分钟前
加密认证库openssl初始附带c/c++的使用源码
c语言·网络·c++·openssl
User_芊芊君子11 分钟前
【C语言经典算法实战】:从“移动距离”问题看矩阵坐标计算
c语言·算法·矩阵
虾球xz1 小时前
游戏引擎学习第243天:异步纹理下载
c++·学习·游戏引擎
wolf犭良1 小时前
37、aiomysql实操习题
开发语言·python·算法
xin007hoyo1 小时前
算法笔记.spfa算法(bellman-ford算法的改进)
数据结构·笔记·算法
向哆哆1 小时前
Java 加密与解密:从算法到应用的全面解析
java·开发语言·算法
uhakadotcom2 小时前
刚发布的PyTorch 2.7提供了什么 新特性
算法·面试·github
新生农民2 小时前
30分钟解决8道算法题
java·数据结构·算法
bbc1212263 小时前
2025/4/23 心得
数据结构·算法
Brookty4 小时前
【数据结构】Map与Set结构详解
数据结构