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;
    }
};
相关推荐
神也佑我橙橙12 分钟前
Thrift 简单介绍
算法
simon_skywalker18 分钟前
线性代数及其应用习题答案(中文版)第二章 矩阵代数 2.1 矩阵运算(2)
线性代数·算法·矩阵
jiayong2320 分钟前
数据结构时间复杂度完全解析
数据结构
REDcker27 分钟前
JS 与 C++ 语言绑定技术详解
开发语言·javascript·c++
June`27 分钟前
C++11新特性全面解析(三):智能指针与死锁
开发语言·c++
断剑zou天涯32 分钟前
【算法笔记】Manacher算法
java·笔记·算法
monster000w1 小时前
大模型微调过程
人工智能·深度学习·算法·计算机视觉·信息与通信
小小晓.1 小时前
Pinely Round 4 (Div. 1 + Div. 2)
c++·算法
SHOJYS1 小时前
学习离线处理 [CSP-J 2022 山东] 部署
数据结构·c++·学习·算法
biter down2 小时前
c++:两种建堆方式的时间复杂度深度解析
算法