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;
    }
};
相关推荐
qizayaoshuap18 分钟前
# ❌ 井字棋 — 鸿蒙ArkTS Minimax AI算法与博弈系统设计
人工智能·算法·华为·harmonyos
皓月斯语1 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet1 小时前
树状结构在查询优化中的作用与实现细节7
算法
徐凤年_2 小时前
rog_map参数理解
算法
春日见2 小时前
算法与数据结构----哈希表
数据结构·人工智能·算法·机器学习·自动驾驶·哈希算法·散列表
萌动的小火苗2 小时前
嵌入式开发中的栈与队列:任务调度为什么依赖数据结构
数据结构·c++·单片机·嵌入式硬件
叩码以求索2 小时前
统计按位或能得到最大值的子集数目(一)
数据结构·算法
tachibana23 小时前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode
星恒随风3 小时前
C++ STL 栈详解:stack 的使用、经典题目与简单模拟实现
开发语言·数据结构·c++·笔记·学习
txzrxz3 小时前
单调队列讲解
数据结构·c++·算法·单调队列