Leetcode Note: Missing Number
I. Description
Given an array containing n distinct numbers taken from0, 1, 2, ..., n, Find the one that is missing from the array.
For example,
Givennums = [0, 1, 3]Return2.
Note:
Your algorithm shocould run in linear runtime complexity. cocould you implement it using only constant extra space complexity?
Ii. Question Analysis
The general idea is to give0, 1, 2, ..., n, SelectednTo find the missing number in the array. A simple example is provided.
The question requires that the algorithm can meet the linear time complexity and constant space complexity.
Because the elements in the array are not equal and only one element is missing, a simple idea is to find0TonBeforenAnd subtract the sum of the elements in the array to get the missing number.
If bitwise operations are used, this question is of the same type as the singe number. The first step to deformation is to convert 0, 1, 2 ,..., N is added to this array again.
Iii. Sample Code
// Class Solution for the sum of the arithmetic difference series {public: int missingNumber (vector
& Nums) {int n = nums. size (); if (n <1) return 0; int completeSum = n * (n + 1)/2, currSum = 0; for (int I = 0; I <n; ++ I) currSum + = nums [I]; return completeSum-currSum ;}};
// Bitwise operation class Solution {public: int missingNumber (vector
& Nums) {int ans = 0; for (vector
: Size_type I = 0; I <nums. size (); ++ I) {ans ^ = nums [I];} for (int I = 0; I <= nums. size (); ++ I) {ans ^ = I;} return ans ;}};
Iv. Summary
The conditions given for this question are relatively loose. For example, the values are not repeated. You can use the sum method of the equals difference series to quickly find the missing number, which can be achieved in just a few minutes, but there is no practical value. You can try the exclusive or operation to solve this problem.