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;
    }
};
相关推荐
别动我齐刘海3 分钟前
Day6 unitree_G1人形机器人GMR—— MotionInput
c语言·c++·人工智能·学习·机器学习·机器人·github
Hi李耶20 分钟前
【LeetCode】541.反转字符串 II
算法·leetcode·职场和发展
shylyly_23 分钟前
104.二叉树的最大深度
数据结构·算法·104.二叉树的最大深度
AI科技星33 分钟前
曲率‑挠率与 $\boldsymbol{\omega/c}$ 的关系、精算验证及其物理意义
c语言·开发语言·线性代数·算法·决策树·机器学习·ai科技星
Henry Zhu1231 小时前
C++17 `weak_from_this` 详解:让对象安全地观察自己
c++
沐籽李1 小时前
HuDiff在抗体人源化项目中的工程化落地
人工智能·算法·aidd·抗体设计
依然范特东1 小时前
强化学习笔记6--IS、PPO、TD、DQN、Actor-Critic
笔记·算法
一次旅行3 小时前
RLHF全链路深度解析:Reward Model数学推导+PPO完整实战,对比GRPO轻量化方案
人工智能·算法·机器学习
Wang's Blog3 小时前
AI Agent白手起家29: Few Shot 提示词工程实战
人工智能·算法
June`4 小时前
warp shuffle指令
c++·人工智能·算法·cuda