LeetCode Brush Questions, Simple Questions (Issue 23)

table of Contents

Question 1: Integer conversion

Question 2: Repeated substring

Question 3: Range Sum 2

Question 4: Reverse the number

Question 5: Convert numbers to hexadecimal

Question 6: Compare characters with backspace

Question 7: The maximum product of three numbers

Question 8: Beads' calculation

Question 9: Rotating string

Question 10: Location of larger groups


LeetCode regularly brushes questions, 10 questions per issue. Comrades with heavy business can look at the ideas I shared. It is not the most efficient solution, but only seeks to improve each other.

Question 1: Integer conversion

The test questions are as follows:

Answer ideas:

XOR operation.

Answer (C language):

int convertInteger(int A, int B){
    int res=0;

    unsigned int tmp = A^B;

    while(tmp){
        if(tmp&1==1){
            res=res+1;
        }
        
        tmp>>=1;
    }

    return res;
}

The operating efficiency is as follows:


Question 2: Repeated substring

The test questions are as follows:

Answer ideas:

Answer (C language):

bool repeatedSubstringPattern(char* s) {
    int n = strlen(s);

    for (int i = 1; i * 2 <= n; ++i) {
        if (n % i == 0) {
            bool match = true;

            for (int j = i; j < n; ++j) {
                if (s[j] != s[j - i]) {
                    match = false;
                    break;
                }
            }
            
            if (match) {
                return true;
            }
        }
    }

    return false;
}

The operating efficiency is as follows:


Question 3: Range Sum 2

The test questions are as follows:

Answer ideas:

The simplest way to do this is to find the smallest number in the first column and the second column of the given two-dimensional matrix, because the two numbers in each row of the array can be divided into a rectangle, and the last and the largest number must be the same The overlapping part of, so just find the minimum value of each column of the array, and the product is what you want.

Answer (C language):

int maxCount(int m, int n, int** ops, int opsSize, int* opsColSize){
    int min_c = m, min_r = n;

    for(int i = 0;i < opsSize;i++){
        if(ops[i][0] < min_c){
            min_c = ops[i][0];
        }
        if(ops[i][1] < min_r){
            min_r = ops[i][1];
        }
    }

    return min_c * min_r;
}

The operating efficiency is as follows:


Question 4: Reverse the number

The test questions are as follows:

Answer (C language):

void toBit(int num, int *val) {
    int i = 0;
    while(num) {
        val[i] = num & 1;
        num >>= 1;
        i++;
    }
}

int reverseBits(int num){
    int val[32] = {0};
    toBit(num, val);
    
    int count = 0;
    int countPre = 0;
    int max = 0;
    for (int i = 0; i < 32; i++) {
        if (val[i] == 1) {
            count++;
        } 
        else {
            if (countPre + count + 1 > max) {
                max = countPre + count + 1;
            }
            countPre = count;
            count = 0;
        }
    }

    return max;
}

The operating efficiency is as follows:


Question 5: Convert numbers to hexadecimal

The test questions are as follows:

Answer ideas:

Take the remainder, divide by 16 (0X0F), load into the array, and then reverse.

Answer (C language):

char g_stack[16 + 1] = {0};
void swap(char *a, char *b) {char t = *a; *a = *b; *b = t; }

char * toHex(int num) {
    int top = -1;
    unsigned int n = num;
    char index[] = "0123456789abcdef";

    // 这里用do...while()而不是while(),能直接覆盖num为0的情况
    do {
        g_stack[++top] = index[n % 16];
        n /= 16;
    } while (n != 0);
    g_stack[top + 1] = '\0';

    int lo = 0, hi = top;

    while (lo < hi) {
        swap(&g_stack[lo++], &g_stack[hi--]);
    }
    
    return g_stack;
}

The operating efficiency is as follows:


Question 6: Compare characters with backspace

The test questions are as follows:

Answer ideas:

Using a double pointer, when encountering a'#', the subscript is reduced by one, and the previous character is deleted; other characters increase the subscript count in turn; get a new string, and then compare whether the strings are the same.

Answer (C language):

int deletebackspace(char *str,int size){
    if(str==NULL||size==0){
        return 0;
    }

    int index = 0;

    for(int i=0;i<size;i++){
        if(str[i] != '#'){
            str[index++] = str[i];
        }
        else{
            if(index>0){
                index--;
            }
        }
    }

    return index;
}

bool backspaceCompare(char * S, char * T){
    int slen = deletebackspace(S,strlen(S));
    int tlen = deletebackspace(T,strlen(T));

    if(slen != tlen){
        return false;
    }
    else{
        for(int i=0;i<slen;i++){
            if(S[i] != T[i]){
                return false;
            }
        }
        
        return true;
    }
}

The operating efficiency is as follows:


Question 7: The maximum product of three numbers

The test questions are as follows:

Answer ideas:

We sort the array in ascending order. If all the elements in the array are non-negative numbers, then the answer is the product of the last three elements.

If there are negative numbers in the array, then we also need to consider the product contains negative numbers. Obviously choosing the smallest two negative numbers and the largest positive number is optimal, that is, the product of the first two elements and the last element.

Answer (C language):

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

int Max(int a, int b)
{
    return a > b ? a : b;
}

int maximumProduct(int* nums, int numsSize){
    qsort(nums, numsSize, sizeof(int), Compare);
    
    return Max(nums[numsSize - 1] * nums[numsSize -2] * nums[numsSize - 3], nums[numsSize - 1] * nums[0] * nums[1]);
}

The operating efficiency is as follows:


Question 8: Beads' calculation

The test questions are as follows:

Answer (C language):

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* masterMind(char* solution, char* guess, int* returnSize){
    returnSize[0] = 2;
    int dict[26] = {0}, *res = (int *)malloc (sizeof (int) * 2);
    res[0] = res[1] = 0;

    for (int i = 0; solution[i] != '\0'; ++i) {
        dict[solution[i] -'A']++;
        if (guess[i] == solution[i]) res[0]++;
    }

    for (int i = 0; solution[i] != '\0'; ++i) {
        if (dict[guess[i] - 'A']) {
            dict[guess[i] - 'A']--;
            res[1]++;
        }
    }
    
    res[1] -= res[0];
    return res;
}

The operating efficiency is as follows:


Question 9: Rotating string

The test questions are as follows:

Answer (C language):

bool rotateString(char * A, char * B){
    int len = strlen(A);

    if(strlen(B) != len) return false;
    if(strcmp(A, B) == 0) return true;

    for(int i = 0; i < len; i++) {
        if(A[0] == B[i]) {
            int j;
            
            for(j=0; j < len; j++) {
                if(j<i && A[j+len-i] != B[j]) {
                    break;
                }
                if(j >= i && A[j-i] != B[j]) {
                    break;
                }
            }

            if(j == len) {
                return true;
            }
        }
    }

    return false;
}

The operating efficiency is as follows:


Question 10: Location of larger groups

The test questions are as follows:

Answer (C language):

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** largeGroupPositions(char * S, int* returnSize, int** returnColumnSizes){
    int size = 0;
    int len =strlen(S);

    if(len < 3){
        *returnSize = 0;
        ** returnColumnSizes = 0;
        return 0;
    }

    int ** res = (int **)malloc(len * sizeof(int *));
    for(int i=0;i<len;i++){
        res[i] = (int *)calloc(2,sizeof(int));
    }

    for(int i=0; i<len-2 ; i++){
        if( S[i] == S[i+1] && S[i] == S[i+2]){
            (*returnColumnSizes)[size] = 2;
            char temp = S[i];
            res[size][0]=i;
            i+=3;
            while(temp == S[i] && i<len) i++;
            res[size][1]=--i;                   //由于循环体内有i++,此处的S[i]已经是新值的起始点,为了一致,应退回1
            size++;   
        }
    }
    
    *returnSize = size;
    return res;
}

The operating efficiency is as follows:

Guess you like

Origin blog.csdn.net/m0_38106923/article/details/108213568