How are you uu from CSDN, today, Xiao Yalan has opened a new column, and will write questions on Leetcode in the future, try to write one every day, please supervise me! ! ! Alright, let's enter the world of Leetcode
There are many solutions to this question, and Xiao Yalan will analyze it carefully for you next! ! !
Solution one:
Sort, search in turn, if the next number is not the previous number + 1, then the previous number + 1 is the number that disappeared! ! !
But this method, the time complexity is too high, does not meet the requirements of Likou
Using bubble sort, the time complexity is O(N^2)
Using qsort (quick sort), the time complexity is O(N*logN)
But this question requires a time complexity of O(N)
Well, this method will not work, so Xiao Yalan will not write the code for this method.
Solution two:
XOR Same as 0, different as 1
- First, assign x to 0
- for loop, XOR each element of x and nums array
- Then another for loop, let x and the number from 0 to numsSize XOR
- The final answer is the number that appears only once
- The result of the final XOR is the disappearing number we requested
int missingNumber(int* nums, int numsSize)
{
int i=0;
int x=0;
for(i=0;i<numsSize;i++)
{
x^=nums[i];
}
for(i=0;i<numsSize+1;i++)
{
x^=i;
}
return x;
}
Solution three:
using mathematical formulas
The formula for calculating the sum of the first n terms of the arithmetic sequence is: Sn=n*(n+1)/2
After summing, subtract all the values in the nums array, and the final result is the number that disappears
int missingNumber(int* nums, int numsSize)
{
size_t i=0;
int x=numsSize*(1+numsSize)/2;
for(i=0;i<numsSize;i++)
{
x-=nums[i];
}
return x;
}
Alright, this is the end of Xiao Yalan's experience in brushing the questions today, let's continue to work hard! ! !