[problem solving report] lecture 100 on zero basics of algorithms (Lecture 31) multidimensional enumeration - Introduction

preface

Original link: Lecture 100 on zero basis of algorithms (Lecture 31) multidimensional enumeration (I) - Introduction

concept

The linear enumeration mentioned before is to count again to solve the problem. Then multidimensional enumeration needs multiple loops to solve the problem.

int i, j, k;
for(i = 0; i < x; ++i) {
    for(j = 0; j < y; ++j) {
    	for(k = 0; k < z; ++k) {
        	....
        }
    }
}

392. Judgment subsequence

Original title link: 392. Judgment subsequence

code

Cycle again. When * s and * t do not reach the end, if the current position characters are the same, let t go back.

When the loop exits, * s is' \ 0 ', and the reverse is true.

bool isSubsequence(char * s, char * t)
{
    while (*s && *t)
    {
        if (*s == *t)
        {
            s++;
        }
        t++;
    }

    return !*s;
}

240. Search two-dimensional matrix II

Original title link: 240. Search two-dimensional matrix II

analysis

Because the rows and columns of the matrix are arranged in ascending order, you can start from the upper right corner of the matrix.

If the current position is equal to target, exit;
If the current position is > target, the current column will be looked forward because it is arranged in ascending order;
If the current position < target, the number of rows will be changed directly due to the ascending arrangement.

In this way, each change is to change the entire row and column, which is much faster than enumeration.

code

bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target)
{
    if (NULL == matrix)
        return false;

    int row = 0, col = *matrixColSize - 1;

    while (row < matrixSize && col >= 0)
    {
        if (matrix[row][col] == target)
            return true;
        
        if (matrix[row][col] > target)
        {
            --col;
        }
        else
        {
            ++row;
        }
    }
    return false;   
}

2006. Number of pairs whose absolute value of difference is K

Original title link: 2006. Number of pairs whose absolute value of difference is K

code

Enumerate directly according to the topic requirements

int countKDifference(int* nums, int numsSize, int k)
{
    int count = 0;

    for (int i = 0; i < numsSize - 1; ++i)
    {
        for (int j = i + 1; j < numsSize; ++j)
        {
            if (nums[i] - nums[j] == k || nums[j] - nums[i] == k)
            {
                count++;
            }        
        }
    }
    return count;
}

389. Find a different

Original title link: 389. Find a different

analysis

My approach is to use an array to record the occurrence times of each letter of the original string, and then traverse the changed array. For each character, subtract the corresponding number of characters from the saved array;

If the number of a character is reduced to - 1, it means that the character is found.

code

char findTheDifference(char * s, char * t)
{
    if (NULL == s || NULL == t)
        return 0;
    
    int hash[26] = {0};

    for (int i = 0; i < strlen(s); ++i)
    {
        ++hash[s[i] - 'a'];
    }

    for (int i = 0; i < strlen(t); ++i)
    {
        --hash[t[i] - 'a'];

        if (hash[t[i] - 'a'] < 0)
            return t[i];
    }

    return '';
}

1431. Children with the most candy

Original title link: 1431. Children with the most candy

code

Write directly according to the requirements of the topic

I hate two kinds of people:

  1. Someone who writes code without comments (yes, it seems to be me)
  2. Someone who asks others to write notes...
bool* kidsWithCandies(int* candies, int candiesSize, int extraCandies, int* returnSize)
{
    *returnSize = 0;
    if (candies == NULL)
    return NULL;

    bool* ans = (bool*)malloc(sizeof(bool) * candiesSize);
    if (ans == NULL)
    return NULL;

    int i = 0;
    int max = -1;
    for (i; i < candiesSize; ++i)
    {
        if (max < candies[i])
        {
            max = candies[i];
        }
    }

    for (i = 0; i < candiesSize; ++i)
    {
        if (candies[i] + extraCandies >= max)
        {
            ans[i] = true;
        }
        else
        {
            ans[i] = false;
        }
    }

    *returnSize = candiesSize;
    return ans;
}

1588. Sum of all odd length subarrays

Original title link: 1588. Sum of all odd length subarrays

analysis

If multidimensional enumeration, the time complexity is O(n^3)

If the prefix and are used, the innermost cycle time complexity can be optimized to O(1).

code

int sumOddLengthSubarrays(int* arr, int arrSize)
{
    if (NULL == arr)
        return 0;
    
    int prefixSums[arrSize + 1];
    memset(prefixSums, 0, sizeof(prefixSums));

    for (int i = 0; i < arrSize; i++)
    {
        prefixSums[i + 1] = prefixSums[i] + arr[i];
    }

    int sum = 0;

    for (int start = 0; start < arrSize; ++start)
    {
        for (int length = 1; start + length <= arrSize; length += 2)
        {
            int end = start + length - 1;

            sum += prefixSums[end + 1] - prefixSums[start];
        }
    }

    return sum;
}

1534. Count triples

Original title link: 1534. Count triples

code

You can enumerate multiple dimensions directly according to the topic

int countGoodTriplets(int* arr, int arrSize, int a, int b, int c)
{
    if (NULL == arr)
        return 0;
    
    int count = 0;

    for (int i = 0; i < arrSize; ++i)
    {
        for (int j = i + 1; j < arrSize; ++j)
        {
            for (int k = j + 1; k < arrSize; ++k)
            {
                if (fabs(arr[i] - arr[j]) <= a && fabs(arr[j] - arr[k]) <= b && fabs(arr[i] - arr[k]) <= c)
                {
                    ++count;
                }
            }
        }
    }

    return count;
}

771. Gemstones and stones

Original title link: 771. Gemstones and stones

code

enumeration

int numJewelsInStones(char * jewels, char * stones)
{
    if (jewels == NULL || stones == NULL)
        return 0;

    int jewelsLength = strlen(jewels);
    int stonesLength = strlen(stones);
    int count = 0;

    for (int i = 0; i < stonesLength; ++i)
    {
        for (int j = 0; j < jewelsLength; ++j)
        {
            if (stones[i] == jewels[j])
            {
                count++;
            }
        }
    }

    return count;
}

14. Longest common prefix

Original title link: 14. Longest common prefix

analysis

Two dimensional enumeration and change it on the original string. If the i letter of the string in the first line is different from that in other lines, change the position of i to the end of the string, that is' \ 0 '.

code

char * longestCommonPrefix(char ** strs, int strsSize)
{
    if (NULL == strs || strsSize == 0)
    return NULL;

    for (int i = 0; i < strlen(strs[0]); ++i)
    {
        char c = strs[0][i];
        for (int j = 0; j < strsSize; ++j)
        {
            if (c != strs[j][i])
            {
                strs[0][i] = '\0';
                return strs[0];
            }
        }
    }

    return strs[0];
}

1925. Count the number of square sum triples

Original title link: 1925. Count the number of square sum triples

code

Multidimensional enumeration

int countTriples(int n)
{
    if(n == 1)
        return 0;

    int count = 0;
    for(int i = 1; i < n; i++)
    {
        for(int j = 1; j < n; j++)
        {
            for(int k = 1; k <= n; k++)
            {
                if(i * i + j * j == k * k)
                {
                    count++;
                }
            }
        }
    }
    return count;
}

Exercises

1389. Create the target array in the established order

end

Tags: Algorithm leetcode

Posted on Sat, 20 Nov 2021 15:50:06 -0500 by montana111