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);
}
相關文章
- LeetCode Week 2LeetCode
- LeetCode Week 1LeetCode
- LeetCode Week 3LeetCode
- Week 4 Problems
- 【week4】課堂Scrum站立會議Scrum
- C++ articles:Guru of the Week #4 -- Class Mechantics (轉)C++
- 2024年在職考公Week4【5.27~6.2】
- mini-lsm通關筆記Week1Day4筆記
- leetcode-4LeetCode
- Week 11 Problems
- Leetcode 4SumLeetCode
- 4 Sum leetcode javaLeetCodeJava
- NewStarCTF 2023 公開賽道 WEEK4|MISC 部分WP
- Leetcode 18 4SumLeetCode
- LeetCode-342-4的冪LeetCode
- 學習總結(first week)
- 備戰noip week8
- hgame-week3-web-wpGAMWeb
- HGAME-week2-web-wpGAMWeb
- Newstar_week1-2_wp
- week2—南苑速遞
- Week 8 Problems 幽夜默示錄
- nowcoder Week Contest
- Leetcode 4 Median of Two Sorted ArraysLeetCode
- [LeetCode] 4Sum 四數之和LeetCode
- 4.week 獨立開發挑戰第四周及一個月記錄
- HCI 筆記 | Week 06 Prototyping筆記
- week1技術隨筆
- C++ articles:Guru of the Week #1 (轉)C++
- Guru of the week:#18 迭代指標. (轉)指標
- 24暑集訓Week1
- WEEK5|WEB Unserialize AgainWebAI
- NewStarCTF WEEK5|WEB pppython?WebPython
- LeetCode 4. Median of Two Sorted ArraysLeetCode
- leetcode15&16_3Sum&4SumLeetCode
- LeetCode刷題記錄——day4LeetCode
- 【Python for Everybody(Getting Started with Python)】Week 4 | Review:Chapter 2 題目彙總及個人答案PythonViewAPT
- USYD悉尼大學INFO1110 詳細作業解析Week4 revision