Lituo-Record of brushing questions

189. Rotate array

Given an array of integers nums, rotate the elements in the array to k the  by positions, where is k a non-negative number.

Leetcode icon-default.png?t=N2N8https://leetcode.cn/problems/rotate-array/description/

void rotate(int* nums, int numsSize, int k){
    if(k > numsSize)
    {
        k %= numsSize;
    }
    if(k==0){
         for(int i=0;i<numsSize;++i){
           nums[i]=nums[i];  
         }
    }
    int newArr[numsSize+k];
    int n=0;
    for(int i=0;i<numsSize;++i)
    {
        
        if(i+k<numsSize){
        newArr[i+k]=nums[i];
        }
        else
        {
            newArr[n]=nums[i];
            n++;
        }
    }
    for(int i=0;i<numsSize;++i)
    {
        nums[i]=newArr[i];
    }

}

Although this code can solve the problem when k is equal to 0, there are still problems of newly creating an array and using an additional variable n, which may affect the performance and efficiency of the program. In the case that the number of rotations is not 0, a new array still needs to be created, and two loop operations are performed, which is time-consuming and space-consuming.

Therefore, you can consider using other algorithms or optimization methods to improve the implementation of the code, such as directly performing rotation operations on the original array, without creating a new array, and can avoid the above problems.

void reverse(int*nums,int begin,int end)
{
    while(begin<end)
    {
        int tmp=nums[begin];
        nums[begin]=nums[end];
        nums[end]=tmp;
        begin++;
        --end;
    }
}

void rotate(int* nums, int numsSize, int k){
    //采用三趟倒置的做法
    if(k<numsSize)
    {
        k%=numsSize;
    }
    reverse(nums,0,numsSize-1);
    reverse(nums,0,k-1);
    reverse(nums,k,numsSize-1);
}

The above code implements the rotation operation of the array elements, using the method of three inversion operations. Specifically, for a given array nums, reverse the entire array, then reverse the first k elements, and finally reverse the remaining elements to obtain a new array after rotating the array k steps .


Interview question 17.04. Disappearing numbers

The array numscontains all integers from 0to n, but one of them is missing. Please write code to find that missing integer. Do you have a way to do it in O(n) time?

int missingNumber(int* nums, int numsSize){
    int sum= numsSize*(numsSize+1)/2;
    for(int i=0;i<numsSize;++i){
        sum-=nums[i];
    }
    return sum;
}

The above code also realizes to find the missing number in the given array nums and returns the number. This algorithm uses a mathematical method to calculate the sum of all numbers in the sequence, and then subtracts the sum of all elements in the array nums, and the difference is the missing number.

Specifically, since a number is missing in the nums array, the length of the entire sequence should be numsSize+1. Assuming that the entire sequence contains all integers from 0 to numsSize, then the sum of sequence elements is (numsSize+1)*numsSize/2. Therefore, it is only necessary to traverse the array nums, accumulate the values ​​of nums[i], and then subtract the accumulated sum from the sum, and finally get the missing number.

int Num(int a)
{
    if (a <= 0)
    {
        return 0;
    }
    else
    {
        return a + Num(a - 1);
    }
}

int missingNumber(int* nums, int numsSize) {
    int b = Num(numsSize);
    int c = 0;
    for (int i = 0; i < numsSize; i++)
    {
       c =c + nums[i];
    }
    int d = b - c;
    return d;
}

The above code also realizes to find the missing number in the given array nums and returns the number. The difference from the previous algorithm is that this algorithm uses the recursive function Num to find all sums b of integers from 1 to numsSize, then adds up the values ​​of all elements in the array nums to get c, and finally subtracts c from b to get the missing number .

Specifically, the implementation of the recursive function Num is the same as the first code snippet, but because its time complexity is O(n), it may cause problems such as stack overflow or timeout when calculating a large numsSize. Therefore, the scope of use of this algorithm is limited, and it is only applicable to the case where numsSize is small.

The total time complexity is O(n), and the space complexity is O(1). It should be noted that when calling itself in a recursive function, each call will create a new function stack frame, so the recursive call will occupy a certain amount of memory space, which may cause problems such as stack overflow.


 3. Integer inversion

Given a 32-bit signed integer x, return the result of inverting the numeric portion of x.

Returns 0 if the inverted integer exceeds the range [−231, 231 − 1] of a 32-bit signed integer.
Assume the environment does not allow storing 64-bit integers (signed or unsigned).

int reverse(int x){
    int rev=0;
    while(x!=0){
        if(rev<INT_MIN/10||rev>INT_MAX/10)
        {
            return 0;
        }
        int turn=x%10;
        x/=10;
        rev=rev*10+turn;
    }
    return rev;
}

The goal of this function is to reverse the given integer x, and use the reversed result as the return value of the function. When performing the inversion operation, we need to take out each digit of the integer in turn, and then form them into a new integer in reverse order. For example, for the integer 123456, the inverted result should be 654321.

Specifically, the implementation of this function mainly includes the following steps:

Initialize the reverse result rev to 0, ready to start the reverse operation

int rev = 0;

Enter a while loop, the loop condition is that the integer x is not 0. In each loop, we need to take the last digit of the current integer and append it to the end of the reversed result rev.

while (x != 0) {
    int turn = x % 10;          // 取出最后一位数字
    x /= 10;                    // 去掉最后一位数字
    rev = rev * 10 + turn;      // 将最后一位数字添加到反转结果 rev 的末尾
}

Before updating the reversal result rev, it is necessary to judge whether the current value exceeds the value range of the int type. If it exceeds, 0 is returned directly, indicating that the correct inversion result cannot be obtained.

if (rev < INT_MIN / 10 || rev > INT_MAX / 10) {
    return 0;
}

Here INT_MIN and INT_MAX represent the minimum value and maximum value of int type respectively. If the reversed result rev divided by 10 is less than INT_MIN or greater than INT_MAX, it means that the reversed result has exceeded the value range of the int type, and the correct result cannot be obtained.

It should be noted that when performing integer inversion, since integer inversion involves numerical overflow, the value range of the inversion result needs to be specially judged to ensure that the program can handle all possible situations.

After the loop ends, the reversed result rev is returned.

return rev;

If the input integer is negative, you need to remove the sign bit before inversion, and add a negative sign to the inversion result to get the correct result.

This step can be achieved by adding the following code before the loop starts:

bool negative = false;     // 标记整数是否为负数
if (x < 0) {
    negative = true;
    x = -x;                // 去掉符号位
}

When returning the result, we need to judge whether to add a negative sign to the inverted result according to the sign of the input integer:

if (negative) {
    return -rev;
} else {
    return rev;
}

The above is the detailed explanation of this function. Overall, the implementation of this function is relatively simple, the main difficulty lies in how to deal with the inversion of numbers and numerical overflow.


Guess you like

Origin blog.csdn.net/m0_62338174/article/details/130090796