Easy difficulty 364
Given an array containing the
[0, n]
middlen
numbernums
, find[0, n]
the number in this range that does not appear in the array.
Advanced:
- Can you achieve linear time complexity and only use an extra constant space algorithm to solve this problem?
Example 1:
Input: nums = [3,0,1] Output: 2 Explanation: n = 3, because there are 3 numbers, all numbers are in the range [0,3]. 2 is the missing number because it does not appear in nums.Example 2:
Input: nums = [0,1] Output: 2 Explanation: n = 2, because there are 2 numbers, all numbers are in the range [0,2]. 2 is the missing number because it does not appear in nums.Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1] Output: 8 Explanation: n = 9, because there are 9 numbers, all numbers are in the range [0,9] Inside. 8 is the missing number because it does not appear in nums.Example 4:
Input: nums = [0] Output: 1 Explanation: n = 1. Because there is 1 number, all numbers are in the range [0,1]. 1 is the missing number because it does not appear in nums.
prompt:
n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
nums
All numbers in are unique
1. Sort
For the sequence after sorting, there are two special positions, the beginning and the end, which are specially considered first. Then use a for loop for the rest of the positions, the latter position should be the previous position
class Solution {
public:
int missingNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
if(nums[nums.size()-1] != nums.size()){
return nums.size();
}else if(nums[0] != 0){
return 0;
}
for(int i = 1; i < nums.size(); i++){
if(nums[i] != nums[i-1] + 1){
return nums[i-1]+1;
}
}
return -1;
}
};
2. XOR operation
XOR operation in the official solution:
Perform an XOR operation on each number in the array for 0-n numbers. The unmissed number appears once in [0-n] and the array, and the XOR operation results in 0.
The missing value only appears once, so the final XOR result is the missing value.
This XOR operation can be used to find missing values in other ordered sequences.
class Solution {
public:
int missingNumber(vector<int>& nums) {
int missing = nums.size();
for(int i = 0; i < nums.size(); i++){
missing ^= i ^ nums[i];
}
return missing;
}
};
3. Mathematical summation
Traverse the array once, sum the indices 1 to n, and subtract the array nums[i-1].
This will not overflow, which is a good solution.
class Solution {
public:
int missingNumber(vector<int>& nums) {
int sum = 0;
for(int i = 1; i <= nums.size(); i++){
sum += i;
sum -= nums[i-1];
}
return sum;
}
};