I. Title Description
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one and that's missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
.
Note:
Your algorithm should run in linear runtime complexity. Could implement it using only constant extra space complexity?
Two. Topic analysis
The main idea is, given an 0, 1, 2, ..., n
array of different numbers from which to select, find the n
missing number in the array. And give a simple example.
The algorithm can satisfy the linear time complexity and constant space complexity of the problem.
Since the elements in the array are not equal and only one is missing, a simple idea is to 0
n
get the missing number from the sum of the arithmetic progression before n
and minus the accumulated elements of the array.
If you use bit arithmetic, this problem with singe number is a type, where the deformation is the first need to be 0, 1, 2, ..., n again into this array.
Three. Sample code
//arithmetic progression sumclassSolution { Public:intMissingnumber ( vector<int>& Nums) {intn = nums.size ();if(N <1)return 0;intCompletesum = n * (n +1) /2, Currsum =0; for(inti =0; I < n; ++i) Currsum + = Nums[i];returnCompletesum-currsum; }};
//bit operation class Solution {public : int missingnumber (vector <int > & nums) {int ans = 0 ; for (vector <int ; :: Size_type i = 0 ; I < nums.size (); ++i) {ans ^= nums[i]; } for (int i = 0; I <= nums.size (); ++i) {ans ^= i; } return ans; }};
Four. Summary
The conditions given in this topic are more lenient, such as the values are not duplicated. Directly using the arithmetic progression summation method can quickly find the missing number, only a few minutes to achieve, but no exercise value, you can try to solve the problem using an XOR operation.
Leetcode Note: Missing number