[problem solving report] guidelines of LeetCode zero foundation guide (Lecture 5)

Posted by moreshion on Mon, 13 Dec 2021 07:15:20 +0100

☘ preface ☘

Today is the fourth day of the nine day training. I will record the learning contents and problem solutions and strive to be the class representative of 0.0
be careful!!!! The solution 1 of the problem solution is the solution to be mastered today, and the solution 2 is to study again when there is spare power, involving the following knowledge point 0.0
Link: LeetCode zero foundation guide (Lecture 5)

🧑🏻 About the author: a young man who changed from industrial design to embedded
✨ Contact: 2201891280(QQ)
⏳ Approximate reading time of the full text: 20min

🎁 Main knowledge points

📝 Definition and operation of pointer

🚗 1. Pointer and address

The pointer is the address. In the computer, all the data used for execution are placed in one position, and this position has an identification, that is, the address. In a 32-bit computer, the addressing space is 32 bits, that is, 232. Because it is addressed by bytes, it is just 4GB, and the 64 bit addressing space is as large as 2 ^ 64.
We call the number of bytes in memory address or ` ` pointer. The address starts at 0.

🍛 2. Definition of pointer

In c language, a variable can be used to store pointers, which is called pointer variables. Their relationship is shown in the figure below:
Where p is the pointer variable name, X is the variable name of the pointed variable, and 0x000000FC is the address of X.

🦪 3. Define pointer variables

Defining pointer variables is similar to ordinary variables, except that you need to add * before the variable name.
Our usual definition is:

int *p;
char *p;

Special note: * is added before the variable name. For the mixed definition of pointers and ordinary variables, we can use the following methods:

int b, *p, a;

It defines a pointer and two ordinary variables!

🍣 4. Get address

We use & to represent the address symbol. Code ex amp le:

char x = 'o';
char *p = &x;

So p gets the address of x.

🍤 5. Array address

When I introduced the array yesterday, I actually said that the array name represents the first address. So it can be assigned to p.

int a[] = {5,2,0,1,3,1,4};
int *p = a;

So p we have the address of the array.

🍤 6. Dereference

Dereference is the reverse operation of taking the address, which is to get the element according to the address. Implemented with *

int a;
int *p = &a;
int c = *p;

The above program assigns the value of a to c.

🍚 7. Memory application

In c language, malloc is used to apply for memory, and the incoming parameter is the number of bytes of applied memory. The return value is the first memory address requested. Then forced conversion is required to use.

int *p = (int *) malloc (1024);

Because an int usually occupies 4 bytes, the array space we applied for above is 256 ints.
It can also be written in another way, which is more general.

int *p = (int *) malloc(sizeof(int)*256);

This will make your program more robust, because the int length of different computers may be inconsistent.

🧂 8. Brush question paradigm of force buckle

int *func(int *nums, int numsSize, int *returnSize) {        
    int *ret = (int *)malloc( sizeof(int) * xxx );                
    // TODO                                                             
    *returnSize = xxx;                            
    return ret;                                
}

🥙 9. Concept summary

nounbrief introductionRelated symbols
PointerAddress of variableint *
Get addressVariable - > address&a
DereferenceAddress - > variable*p
Array header addressRepresented by an array namenums
normal formStandard writingLook up

🍗 After class exercises

1470. Rearrange array

1470. Rearrange array
Title Description

Here is an array nums. There are 2n elements in the array, which are arranged in the format of [x1,x2,...,xn,y1,y2,...,yn].
Please rearrange the array in [x1,y1,x2,y2,...,xn,yn] format and return the rearranged array.

thinking

Just select the corresponding element according to parity.

int* shuffle(int* nums, int numsSize, int n, int* returnSize){
    int *ret = (int *) malloc(numsSize*sizeof(int));
    for(int i = 0; i < numsSize; ++i)
        if(i & 1)
            ret[i] = nums[n+i/2];	//Odd numbers are the data in the second half
        else
            ret[i] = nums[(i + 1)/2];	//Even numbers are the data in the first half
    *returnSize = numsSize;
    return ret;
}

1929. Array concatenation

1929. Array concatenation
Title Description

Give you an integer array num of length n. Please construct an answer array ans with a length of 2n. The array subscript counts from 0. For all i with 0 < = i < n, all the following requirements are met:

  • ans[i] == nums[i]
  • ans[i + n] == nums[i]

Specifically, ans is formed by concatenating two nums arrays.
Returns the array ans.

thinking

Cheat and copy the corresponding memory elements directly with memcpy. 0

int* getConcatenation(int* nums, int numsSize, int* returnSize){
    int *ans = (int *) malloc(2*numsSize*sizeof(int));
    memcpy(ans,nums,numsSize*sizeof(int));
    memcpy(&ans[numsSize],nums,numsSize*sizeof(int));
    *returnSize = 2 * numsSize;
    return ans;
}

1920. Building arrays based on permutations

1920. Building arrays based on permutations
Title Description

Give you an array num starting from 0 (subscript also starts from 0). Please build an array ans of the same length, where ans [i] = num [num [i]] is satisfied for each I (0 < = I < num.length). Return the constructed array ANS.
The permutation nums starting from 0 is from 0 to nums An array of different integers of length - 1 (0 and num.length - 1 are also included)

thinking

He can do whatever he asks. The formulas are given in vain --

int* buildArray(int* nums, int numsSize, int* returnSize){
    int *ans =malloc(sizeof(int)*numsSize);
    *returnSize = numsSize;
    for(int i = 0;i < numsSize;i++)
        ans[i] = nums[nums[i]];
    return ans;
}

1480. Dynamic sum of one-dimensional arrays

1480. Dynamic sum of one-dimensional arrays
Title Description

Give you an array nums. The calculation formula of array "dynamic sum" is: runningsum [i] = sum (Num [0]... Num [i]).
Please return the dynamic and of nums.

thinking

He can do whatever he asks. The formulas are given in vain --

int* runningSum(int* nums, int numsSize, int* returnSize){
    for(int i  = 1; i < numsSize; ++i){
        nums[i] += nums[i-1];
    }
    *returnSize = numsSize;
    return nums;
}

Sword finger Offer 58 - II Left rotation string

Sword finger Offer 58 - II Left rotation string
Title Description

The left rotation operation of a string is to transfer several characters in front of the string to the end of the string. Please define a function to realize the function of string left rotation operation. For example, if you enter the string "abcdefg" and the number 2, the function will return the result "cdefgab" obtained by rotating two bits left.

thinking

Although left-handed rotation can be carried out many times, it is a waste of time. So you can use inversion.
In fact, if it is left-handed, it is equivalent to first reversing all, and then reversing the first half and the second half.
For example: ABCDEFG - > gfedcba - > gfedcab - > cdefgab

void Reverse(char *p, char *q){
    if(!p || !q) return;
    while(p < q){
        *p = *p ^ *q;
        *q = *p ^ *q;
        *p = *p ^ *q;
        p++;q--;
    }
}
char* reverseLeftWords(char* s, int n){
    int size = 0;
    while(s[size]) size++;
    Reverse(s,&s[size-1]);//Reverse all
    Reverse(&s[size - n],&s[size - 1]);//Reverse the second half
    Reverse(s,&s[size - 1 - n]);//Reverse the first half
    return s;
}

1108. IP address invalidation

1108. IP address invalidation
Title Description

Give you a valid IPv4 address and return the invalid version of this IP address.
The so-called invalid IP address is actually "[.]" Instead of each ".".

thinking

To avoid multiple moves, add elements from back to front.

char * defangIPaddr(char * address){
    int len;
    for(len = 0; address[len];++len);//Calculation length
    
    int count = 3;
    char  *ans = malloc(sizeof(char)*(len + count * 2 + 1));

    ans[len + count*2] = 0;//Add Terminator

    for(int i = len - 1; i >= 0; --i){
        if(address[i] != '.')   ans[i + count*2] = address[i];//Does not mean that the point is directly added
        else{//Add [.]
            ans[i + count*2] = ']';
            ans[i + count*2 - 1] = address[i];
            ans[i + count*2 - 2] = '[';
            count--;
        }
    } 
    return ans;
    
}

Sword finger Offer 05 Replace spaces

Sword finger Offer 05 Replace spaces
Title Description

Please implement a function to replace each space in the string s with "% 20".

thinking

Same as above, because% 20 is longer than spaces. So insert from back to front.

char* replaceSpace(char* s){
    int count = 0,size = 0;
    for(int i = 0;s[i];i++){
        if(s[i] == ' ') count++;
        size++;
    }

    int p1 = size,p2 = size + 2*count;
    char *ans = malloc(sizeof(char)*(p2 + 1 ));
    while(p1 >= 0){
        if(s[p1] != ' ')    ans[p2--] = s[p1--];
        else{
            ans[p2--] = '0';
            ans[p2--] = '2';
            ans[p2--] = '%';
            p1--;
        }
    }
    return ans;
}

1365. How many numbers are smaller than the current number

1365. How many numbers are smaller than the current number
Title Description

Give you an array nums. For each element nums[i], please count the number of all numbers smaller than it in the array.
In other words, for each num [i], you must calculate the number of effective J, where j satisfies J= I and num [J] < num [i].
Returns the answer as an array.

thinking

Just scan from back to front and insert statistics.

int* smallerNumbersThanCurrent(int* nums, int numsSize, int* returnSize){
    int *ans = malloc(numsSize*sizeof(int));
    for(int i = 0; i < numsSize; ++i){
        int sum = 0;
        for(int j = 0; j < numsSize; j++)
            if(nums[i] > nums[j]) sum++;
        ans[i] = sum;
    }
    *returnSize = numsSize;
    return ans;
}

Sword finger Offer 17 Print from 1 to maximum n digits

Sword finger Offer 17 Print from 1 to maximum n digits
Title Description

Enter the number N and print out the decimal number from 1 to the maximum n digits in order. For example, if you enter 3, 1, 2 and 3 will be printed up to the maximum 3 digits 999.

thinking

Just scan from back to front and insert statistics.

int* printNumbers(int n, int* returnSize){
    *returnSize = (int) pow(10,n) - 1;
    int *ans = (int *)malloc((*returnSize)*sizeof(int));
    for(int i = 0; i < *returnSize; ++i)
        ans[i] = i + 1;
    return ans;
}

1389. Create the target array in the established order

1389. Create the target array in the established order
Title Description

Here are two integer arrays nums and index. You need to create the target array according to the following rules:

  • The target array target was initially empty.
  • Read num [i] and index[i] from left to right, and insert the value num [i] at the subscript index[i] in the target array.
  • Repeat the previous step until there are no elements to read in num and index.

Please return the target array.
The title ensures that the number insertion position always exists.

thinking

Create a function for inserting functions, and then insert them in turn.

void inserst(int *ans,int *size,int weizhi,int k){
    //printf("%d %d",weizhi,*size);
    int wei = (*size)++;
    while(wei != weizhi)    ans[wei] = ans[wei - 1],wei--;
    ans[weizhi] = k;//insert
}
int* createTargetArray(int* nums, int numsSize, int* index, int indexSize, int* returnSize){
    int *ans = malloc(sizeof(int) * numsSize);
    *returnSize = 0;
    for(int i = 0;i < indexSize;i++)
        inserst(ans,returnSize,index[i],nums[i]);
    return ans;
}

📑 Write at the end

Today, I completed the clock out on the fourth day. Today's algorithm notes also happen to have pointers. You say it's a coincidence. Hahaha, I really didn't mean to, but I really recommend reading it. Ten thousand words long. Please give me a certain time. After writing, I put the top link in the comment area 0.0

Topics: C++ Algorithm leetcode