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;
    }
};
相关推荐
OPEN-F3 分钟前
C++11/14新特性精讲:移动语义与智能指针实战
开发语言·c++·算法
闭月之泪舞14 分钟前
C++编程学习
c++·学习
lisin-lee-cooper21 分钟前
【leetcode658】有序数组找出k个最接近x的数
java·数据结构·算法
sunburn-29 分钟前
Java堆(Heap)详解与实战教学
java·开发语言·数据结构·ide·算法
智碳能碳管理平台1 小时前
工业能耗台账标准化:能碳管理系统的数据口径怎么设计
算法·能碳管理系统·智碳能碳管理平台·企业能碳管理系统·碳排放核算软件·绿色工厂申报saas·能碳管理平台
带多刺的玫瑰2 小时前
Leecode#15刷题之三数之和
算法·leetcode·职场和发展
圣保罗的大教堂2 小时前
leetcode 877. 石子游戏 中等
leetcode
哭泣方源炼蛊2 小时前
并查集进阶 P1(带权并查集,并查集分类)
数据结构·c++·算法·二进制·带权并查集
牧羊人.3332 小时前
动手学深度学习 02 | 手写数字识别
图像处理·人工智能·深度学习·算法
武帝为此2 小时前
【InnoDB存储引擎介绍】
数据库·算法