LeetCode, Simple (Issue 13)

Posted by PastorHank on Wed, 24 Jun 2020 03:57:16 +0200

Catalog

Topic 1: Minimum distance of characters

Question 2: Baseball Match

Question 3: Determining whether each other is character rearrangement

Topic 4: Perimeter of an island

Topic 5: The intersection of two arrays

Title 6: Calculating prime numbers

Question 7: Rotating Array

Question 8: The average number of layers of a binary tree

Topic 9: Building a Binary Search Tree

Question 10: Candy distribution

LeetCode regularly brushes the questions, with 10 questions in each issue. Business-heavy comrades can see the ideas I share. They are not the most efficient solution, they only want to improve each other.

Topic 1: Minimum distance of characters

The test requirements are as follows:

Solution ideas:

Traversing left to right, recording the position prev where the last character C appeared, the answer is i - prev.

If you want to traverse from the right and record the position prev where the last character C appeared, the answer is prev - i.

The minimum of these two values is the answer.

Answer (C language):

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* shortestToChar(char * S, char C, int* returnSize){
    int tmp1,tmp2;
    int len = strlen(S);
    int* ret = (int *)malloc(len * sizeof(int));

    for(int i = 0; i < len; i++)
    {
        tmp1 = 0;
        for(int j = i; j >= 0; j--)
        {
            if (S[j] != C) {
                if (j == 0) {
                    tmp1 = len;
                } else {
                    tmp1++;
                }
            } else {
                break;
            }
        }

        tmp2 = 0;
        for(int j = i; j < len; j++)
        {
            if (S[j] != C) {
                if (j == len-1) {
                    tmp2 = len;
                } else {
                    tmp2++;
                }
            } else {
                break;
            }
        }

        ret[i] = tmp1 < tmp2 ? tmp1 : tmp2;
    }

    *returnSize = len;
    return ret;
}

The operating efficiency is as follows:

Question 2: Baseball Match

The test requirements are as follows:

Solution ideas:

Stack ideas.

Answer (C language):

int calPoints(char ** ops, int opsSize){
    int arr[1000]={0};
    int score = 0,i = 0,j = 0;

    while(i < opsSize){
        switch(ops[i][0]){
            case 'C':
                arr[j-1]=0;
                j-=2;
                break;

            case 'D':
                arr[j]=arr[j-1]*2;
                break;

            case '+':
                arr[j]=arr[j-1]+arr[j-2];
                break;

            default:
                //String type to integer type
                arr[j]=atoi(ops[i]);
                break;
        }

        j++;
        i++;
    }

    for(int i=0;i<j;i++){
        score+=arr[i];
    }

    return score;
}

The operating efficiency is as follows:

Question 3: Determining whether each other is character rearrangement

The test requirements are as follows:

Answer (C language):

bool CheckPermutation(char* s1, char* s2){
    int i = 0,j = 0,s1Len = 0,s2Len = 0;
    s1Len=strlen(s1);
    s2Len=strlen(s2);

    if(s1Len != s2Len){
         return false;
    }

    char letter[26]={0};

    for(i=0;i<s1Len;i++){
       letter[s1[i]-'a']++;
    }

    for(i=0;i<s2Len;i++){
       letter[s2[i]-'a']--;
    }

    for(i=0;i<26;i++){
        if(letter[i]!=0){
           return false;
        }
    }

    return true;
}

The operating efficiency is as follows:

Topic 4: Perimeter of an island

The test requirements are as follows:

Solution ideas:

Each island with four directions around +4 is -1.

Answer (C language):

int islandPerimeter(int** grid, int gridSize, int* gridColSize){
    int circle = 0;
    
    for (int i = 0; i < gridSize; i++) {
        for (int j = 0; j < (*gridColSize); j++) {
            if (grid[i][j] == 1) {
                circle +=4;
                if (i > 0 && grid[i-1][j] == 1) {
                    circle--;
                }
                if ((i + 1) < gridSize && grid[i + 1][j] == 1){
                    circle--;
                }
                if (j > 0 && grid[i][j - 1] == 1) {
                    circle--;
                }
                if ((j + 1) < (*gridColSize) && grid[i][j + 1] == 1){
                    circle--;
                }
            }
        }        
    }

    return circle;
}

The operating efficiency is as follows:

Topic 5: The intersection of two arrays

The test requirements are as follows:

Solution ideas:

Use a hash table query: map array 1, use array elements as subscripts, and hash corresponding elements ++; traverse array 2, also use array elements as subscripts, to determine if the element at that subscript has a value (if it exists in array 1).

Answer (C language):

The operating efficiency is as follows:

Title 6: Calculating prime numbers

The test requirements are as follows:

Solution ideas:

A prime number is a natural number that has no more factors than 1 except 1 and itself.

Eladoser screening:

Answer (C language):

int countPrimes(int n)
{
    int *isPrime = (int*)malloc(sizeof(int) * n);
    memset(isPrime, 0, sizeof(int) * n);
    int cnt = 0;

    for(int i = 2; i < n; i++){
        if(isPrime[i] == 0){
            cnt++;
            for(int j = i + i; j < n; j += i){  //Sieve out multiples of i
                isPrime[j] = 1;
            }
        }
    }

    return cnt;
}

The operating efficiency is as follows:

Question 7: Rotating Array

The test requirements are as follows:

Solution ideas:

Use methods that invert arrays, such as when k is 3:

Original Array: 1 2 3 4 5 6 7

After inverting all numbers: 7 6 5 4 3 2 1

Reverse the first k digits: 5 6 7 4 3 2 1

After inversion of n-k digits: 56 7 1 2 3 4 -->Result

Answer (C language):

static void reverse(int* nums, int numsSize, int start, int end)
{
    int temp = 0;

    while (start < end)
    {
        temp = nums[start];
        nums[start] = nums[end];
        nums[end] = temp;
        start++, end--;
    }
}

void rotate(int* nums, int numsSize, int k){
    k = k % numsSize;
    reverse(nums, numsSize, 0, numsSize - 1);
    reverse(nums, numsSize, 0, k - 1);
    reverse(nums, numsSize, k, numsSize - 1);
}

The operating efficiency is as follows:

Question 8: The average number of layers of a binary tree

The test requirements are as follows:

Answer (C language):

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

 void helper(struct TreeNode* root, double* sum, double* count, int index, int* head){
     if(root==NULL){
        return;
    }
    sum[index] += root->val;
    count[index]++;
    (*head) = fmax(*head, index);
    helper(root->left, sum, count, index+1, head);
    helper(root->right, sum, count, index+1, head);
 }

double* averageOfLevels(struct TreeNode* root, int* returnSize){
    int NUM = 10000;
    double* sum = (double*)calloc(NUM, sizeof(double));
    double* count = (double*)calloc(NUM, sizeof(double));

    int head = 0;
    helper(root, sum, count, 0, &head);
    double* ret = (double*)malloc((head+1)*sizeof(double));
    for(int i=0; i<head+1; i++) {
        ret[i] = sum[i]/count[i];
    }

    *returnSize = head+1;
    
    return ret;
}

The operating efficiency is as follows:

Topic 9: Building a Binary Search Tree

The test requirements are as follows:

Answer (C language):

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

struct TreeNode* trimBST(struct TreeNode* root, int L, int R){
    if (NULL == root)
    {
        return NULL;
    }

    if (root->val < L)
    {
        return trimBST(root->right, L, R);
    }

    if (R < root->val)
    {
        return trimBST(root->left, L, R);
    }

    root->left = trimBST(root->left, L, R);
    root->right = trimBST(root->right, L, R);

    return root;
}

The operating efficiency is as follows:

Question 10: Candy distribution

The test requirements are as follows:

Answer (C language):

int cmpfunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

int distributeCandies(int* candies, int candiesSize){
    int cou = 0;

    qsort(candies, candiesSize, sizeof(int), cmpfunc);
    
    for(int i = 0,j = 1;i < candiesSize-1;i++,j = i+1){
        if(candies[i] != candies[j]){
            cou++;
        }
    }

    cou++;

    if(cou < candiesSize/2){
        return cou;
    }

    return candiesSize/2;
}

The operating efficiency is as follows:

Topics: C