LeetCode Week 0
warm up, 希望可以坚持下来
问题集合
1. Hamming Distance (Easy 461)
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
Solution:
int hammingDistance(int x, int y) {
int diff = x^y;
int distance = 0;
while (diff) {
distance += diff & 1;
diff >>= 1;
}
return distance;
}
2.Number Complement (Easy 476)
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
2. You could assume no leading zero bit in the integer’s binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
Solution:
int findComplement(int num) {
int helper = -1;
int complement = num ^ helper;
int mask = 0;
while(num > 0) {
mask = (mask << 1) + 1;
num >>= 1;
}
return complement & mask;
}
3.Keyboard Row (Easy 500)
Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.
Note:
1. You may use one character in the keyboard more than once.
2. You may assume the input string will only contain letters of alphabet.
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Solution:
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
char** findWords(char** words, int wordsSize, int* returnSize) {
*returnSize = 0;
char** result = NULL;
if (wordsSize <= 0) return result;
int rowMap[26] = {1, 2, 2, 1, 0, 1, 1, 1, 0, 1, 1, 1, 2, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 2, 0, 2};
int* saveFlags = (int *)malloc(sizeof(int) * wordsSize);
int cellSize = 0;
for (int i = 0; i < wordsSize; i++) {
int lastRow = -1;
int save = 1;
int len = strlen(words[i]);
for (int j = 0; j < len; j++) {
int row = rowMap[(words[i][j] < 'a' ? (words[i][j] + 32) : words[i][j]) - 'a'];
if (lastRow != -1 && row != lastRow) {
save = 0;
break;
}
lastRow = row;
}
saveFlags[i] = save;
if (save) {
(*returnSize)++;
if (cellSize < len) {
cellSize = len;
}
}
}
if ((*returnSize) > 0) {
// alloc memory
result = (char **)malloc(sizeof(char*) * (*returnSize));
for (int i = 0; i < (*returnSize); i++) {
result[i] = (char *)malloc(sizeof(char) * (cellSize + 1));
}
// copy words
int index = 0;
for (int i = 0; i < wordsSize; i++) {
if (saveFlags[i]) {
strcpy(result[index++], words[i]);
}
}
}
return result;