LeetCode刷題筆記:缺失數字
阿新 • • 發佈:2019-01-03
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;
}
}
}
};