LeetCode刷题笔记:缺失数字

  • Post author:
  • Post category:其他


Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Note:

Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

解题思路

首先我们通过输入的向量可以得到

n

的大小,将原数组排序之后进行遍历,若遍历的下标和数组中的元素不等时,表明此下标即为缺失的值。

Solution

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int n = nums.size() + 1;
        int max = n;
        sort(nums.begin(), nums.end());
        for(int i = 0; i < max; ++i) {
            if(i != nums[i]) {
                return i;
            }
        }
    }
};



版权声明:本文为JRRRJ原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。