LeetCode Week 4

LeetCode Week 4

练腿是最虐的项目,没有之一

问题集合

1.Reverse Words in a String III(Easy 557)

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note:
In the string, each word is separated by single space and there will not be any extra space in the string.

Solution:

char* reverseWords(char* s) {
    int start = 0;
    int length = strlen(s);
    bool findStart = true;

    int i = 0;
    while (i < length) {
        if (findStart) {
            if (s[i] != ' ') {
                start = i;
                findStart = false;
            }
            else {
                i++;
            }
        }
        else {
            if (s[i + 1] == ' ' || s[i + 1] == '\0') {
                reverseWord(s, start, i);
                findStart = true;
            }
            i++;
        }
    }
    return s;
}

void reverseWord(char* s, int start, int end) {
    while (start < end) {
        char tmp = s[start];
        s[start] = s[end];
        s[end] = tmp;

        start++;
        end--;
    }
}

2.Reverse String II (Easy 541)

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
Example:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Note:
1.The string consists of lower English letters only.
2.Length of the given string and k will in the range [1, 10000]
Solution:

char* reverseStr(char* s, int k) {
    int length = strlen(s);

    bool reverse = true;
    for (int i = 0; i * k < length; i++) {
        if (!reverse) {
            reverse = true;
            continue;
        }

        reverseFunc(s, i * k, ((i + 1) * k < length ? (i + 1) * k : length) - 1);
        reverse = false;
    }
    return s;
}

void reverseFunc(char* s, int start, int end) {
    while (start < end) {
        char tmp = s[start];
        s[start] = s[end];
        s[end] = tmp;

        start++;
        end--;
    }
}

3.Island Perimeter (Easy 463)

You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn’t have “lakes” (water inside that isn’t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.

Example:

[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

Answer: 16

Solution:

int islandPerimeter(int** grid, int gridRowSize, int gridColSize) {
    int perimeter = 0;
    for (int i = 0; i < gridRowSize; i++) {
        for (int j = 0; j < gridColSize; j++) {
            if (!grid[i][j]) continue;
            if (i == 0 || grid[i - 1][j] == 0) perimeter++;
            if (i == gridRowSize - 1 || grid[i + 1][j] == 0) perimeter++;
            if (j == 0 || grid[i][j - 1] == 0) perimeter++;
            if (j == gridColSize - 1 || grid[i][j + 1] == 0) perimeter++;
        }
    }
    return perimeter;
}

4.Complex Number Multiplication (Medium 537)

Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note i * i = -1 according to the definition.
Example 1:

Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i * i + 2 * i = 2i, and you need convert it to the form of 0+2i.

Example 2:

Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i * i - 2 * i = -2i, and you need convert it to the form of 0+-2i.

Solution:

char* complexNumberMultiply(char* a, char* b) {
    int x1, y1, x2, y2;
    parse(a, &x1, &y1);
    parse(b, &x2, &y2);

    int resultX = x1 * x2 - y1 * y2;
    int resultY = x1 * y2 + x2 * y1;

    // magic num, haha
    char* result = (char*)malloc(sizeof(char) * 20);
    int index = 0;

    // reverse order
    result[index++] = 'i';
    addResult(result, &index, resultY);
    result[index++] = '+';
    addResult(result, &index, resultX);
    result[index] = 0;

    // reverse
    int x = 0, y = index - 1;
    while(x < y) {
        char tmp = result[x];
        result[x] = result[y];
        result[y] = tmp;
        x++;
        y--;
    }

    return result;
}

void addResult(char* result, int* index, int num) {
    int tmp = num >= 0 ? num : num * -1;
    if (tmp == 0) {
        result[(*index)++] = '0';
    }
    else {
        while(tmp) {
            result[(*index)++] = tmp % 10 + '0';
            tmp /= 10;
        }
        if (num < 0) {
            result[(*index)++] = '-';
        }
    }
}

void parse(char* s, int* x, int* y) {
    int length = strlen(s);
    int pos = -1;
    for (int i = 0; i < length; i++) {
        if (s[i] == '+') {
            pos = i;
            break;
        }
    }

    *x = toNum(s, 0, pos - 1);
    *y = toNum(s, pos + 1, length - 2);
}

int toNum(char *s, int start, int end) {
    int factor = 1;
    if (s[start] == '-') {
        start++;
        factor = -1;
    }

    int result = 0;
    for (int i = start; i <= end; i++) {
        result = result * 10 + s[i] - '0';
    }
    return result * factor;
}

5.Battleships in a Board (Medium 419)

Given an 2D board, count how many battleships are in it. The battleships are represented with ‘X’s, empty slots are represented with ‘.’s. You may assume the following rules:

1.You receive a valid board, made of only battleships or empty slots.
2.Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
3.At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.

Example 1:

X..X
...X
...X

In the above board there are 2 battleships.
Example 2:

...X
XXXX
...X

This is an invalid board that you will not receive - as battleships will always have a cell separating between them.

Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?

Solution:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* productExceptSelf(int* nums, int numsSize, int* returnSize) {
    int *result = (int *) malloc(sizeof(int) * numsSize);
    for (int i = 0; i < numsSize; i++) {
        result[i] = 1;
    }
    *returnSize = numsSize;
    int start2End = 1, end2Start = 1;

    for (int i = 0; i < numsSize; i++) {
        result[i] *= start2End;
        start2End *= nums[i];
        result[numsSize - i - 1] *= end2Start;
        end2Start *= nums[numsSize - i - 1];
    }

    return result;
}

6.Counting Bits (Medium 338)

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.
Example:

For num = 5 you should return [0,1,1,2,1,2].

Follow up:
1.It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
2.Space complexity should be O(n).
3.Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

Solution:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* countBits(int num, int* returnSize) {
    int* result = (int*)malloc(sizeof(int) * (num + 1));
    *returnSize = num + 1;
    // init first member
    result[0] = 0;

    int cubeNum = 1;
    for (int i = 1; i <= num; i++) {
        if (i >= cubeNum * 2) {
            cubeNum *= 2;
        }
        result[i] = 1 + result[i - cubeNum];
    }

    return result;
}

7.Ugly Number II (Medium 264)

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number, and n does not exceed 1690.

Solution:

int nthUglyNumber(int n) {
    if (n <= 0) return 1;
    int* result = (int*)malloc(sizeof(int) * n);
    result[0] = 1;
    int factor2 = 0, factor3 = 0, factor5 = 0;

    for (int i = 1; i < n; i++) {
        result[i] = findMin(result[factor2] * 2, result[factor3] * 3, result[factor5] * 5);

        if (result[i] == result[factor2] * 2) factor2++;
        if (result[i] == result[factor3] * 3) factor3++;
        if (result[i] == result[factor5] * 5) factor5++;
    }

    return result[n - 1];
}

int findMin(int x, int y, int z) {
    return x <= (y <= z ? y : z) ? x : (y <= z ? y : z);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值