2021-3-1

Today, I mainly learned the complexity and did 2 questions. The
complexity is mainly divided into time complexity and space complexity.
Time complexity is not the pursuit of specific execution time, but a rough calculation of the number of times the basic sentence is executed, represented by O() .
It should be noted that
1, the coefficient can be ignored.
2. O(1) does not mean that it is executed once, but the number of executions is the number of times, which is written as O(1). This point requires special attention.
The space complexity calculation is not the size of the space, but the number of variables. At the same time, it should be noted that O(1) does not mean that there is only one variable, but the number of variables is a constant.
Topic 1: A number disappeared in the 0-n array, find a number disappeared in the array.
There are many methods for this question, but for time complexity, it is best to use XOR. By XORing each element in the array that lacks a number, the result of the XOR is XORed with the complete array. , You can get the number of disappearance. (Exclusive OR, the same is 0, the difference is 1, the exclusive OR bitwise operation, one bit
is compared ) Topic 2: In an array, only 2 numbers appear once, and the rest appear twice. Just ask 2 numbers that appear once.
The main idea is
1. XOR each element in the array, and the result will be the XOR result ret of two numbers that appear once.
2. Find out the bit that is 1 in any position of ret, because if one bit is 1, it means that this bit is different for these two numbers.
3. Separate all the numbers in the array according to the bits found. The bits with 1 are in a group, and those with 0 are in a group.
4. XOR the two groups separately, and get the remaining two numbers.
Key code:
while(m<32)
{
if(ret&(1<<m))
break;
else
m++;
} This piece of code is to find the m bit of ret as 1;
for(i=0;i<numssize;i++)
{
if(nums[i]&(1<<i))
x1^=nums[i];
else
x2^=nums[i];
} This piece of code separates the m-bit 1 and m-bit 0, and XOR respectively.
Also note that the return value should be the address of an array, because to get the two numbers, you have to save it with an array, but the size of the array is not known at the beginning, so use dynamic memory to open up a memory, that is, malloc() open up.

Guess you like

Origin blog.51cto.com/15085121/2642980