LeetCode刷题笔记:缺失数字

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;
            }
        }
    }
};

你可能感兴趣的:(LeetCode刷题笔记,LeetCode刷题笔记)