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;
    }
};
相关推荐
半个落月1 小时前
从递归到快速排序:用 JavaScript 把分治思想讲明白
javascript·算法·面试
小月土星2 小时前
JavaScript 快速排序:从 pivot、双指针到分治思想
javascript·算法·面试
小月土星2 小时前
JavaScript 递归入门:从 1 到 n 求和,再到数组扁平化
javascript·算法·面试
To_OC18 小时前
LC 1 两数之和:面试第一道必考题,暴力解法直接被面试官 pass
javascript·算法·leetcode
鱼鱼不愚与1 天前
《原来如此 | 第01期:为什么导航软件能预测红绿灯倒计时?》
算法
博客18001 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴1 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
复杂网络1 天前
论最小 Agent 计算机的形态
算法
kisshyshy2 天前
🍦 雪糕、食堂、火车厢:三幅漫画吃透栈、队列与链表
javascript·算法