LeetCode题解(一)
LeetCode题解(一)
Counting Bits
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:
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?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
class Solution {
public:
vector<int> countBits(int num) {
vector<int> dp(num+1);
dp[0] = 0;
for (int i=1; i<=num; i++)
{
if (i%2)
dp[i] = dp[i/2]+1;
else
dp[i] = dp[i/2];
}
return dp;
}
};
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* countBits(int num, int* returnSize) {
*returnSize = num + 1;
int* result = (int*)malloc(sizeof(int) * (num + 1));
result[0] = 0;
for (int i = 1; i <= num; ++i) {
if (i % 2) {
result[i] = result[i / 2] + 1;
} else {
result[i] = result[i / 2];
}
}
return result;
}
Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
class Solution {
public:
string& reverseString(string& s) {
std::reverse(s.begin(), s.end());
return s;
}
};
char* reverseString(char* s) {
int len = strlen(s);
for (int i = 0; i < len / 2; ++i) {
s[len] = s[i];
s[i] = s[len-i-1];
s[len-i-1] = s[len];
}
s[len] = '\0';
return s;
}
Power of Four
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
class Solution {
public:
bool isPowerOfFour(int num) {
return num && (int(log10(num) / log10(4)) - log10(num) / log10(4) == 0);
}
};
bool isPowerOfFour(int num) {
return num && ((int)(log10(num) / log10(4)) - log10(num) / log10(4) == 0);
}
Swap Node in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* result = !head ? head : (!head->next ? head : head->next);
ListNode* tmp = NULL;
while (head && head->next) {
if (tmp)
tmp->next = head->next;
tmp = head->next;
head->next = tmp->next;
tmp->next = head;
tmp = head;
head = head->next;
}
return result;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
struct ListNode* result = !head ? head : (!head->next ? head : head->next);
struct ListNode* tmp = NULL;
while (head && head->next) {
if (tmp)
tmp->next = head->next;
tmp = head->next;
head->next = tmp->next;
tmp->next = head;
tmp = head;
head = head->next;
}
return result;
}
Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
int strStr(char* haystack, char* needle) {
char* tmp = haystack;
const int len= strlen(needle);
if (!len)
return 0;
for(; (tmp = strchr(tmp, *needle)) != 0; ++tmp) {
if (strncmp(tmp, needle, len) == 0) {
return tmp - haystack;
}
}
return -1;
}
Word Pattern
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Examples:
pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
pattern = “abba”, str = “dog dog dog dog” should return false.
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
bool wordPattern(char* pattern, char* str) {
if (!pattern || !str || pattern[0] == '\0' || str[0] == '\0')
return false;
int p_len = strlen(pattern);
int s_len = strlen(str);
char p[p_len], s2p[p_len];
int s_index[p_len];
s_index[0] = 0;
int group = 1;
for (int i = 0; i < s_len; ++i) {
if (str[i] == ' ') {
str[i] = '\0';
s_index[group] = i + 1;
++group;
}
}
if (group != p_len) // str按‘ ’分割的组数与pattern字符数不同时
return false;
int count = 0; // 统计pattern中不相同的字符数
for (int i = 0; i < p_len; ++i) {
s2p[i] = -1;
bool flag = true;
for (int j = 0; j < count; ++j) {
if (pattern[i] == p[j]) {
flag = false;
break;
}
}
if (flag) {
p[count] = pattern[i];
++count;
}
}
int k = 0; // 将字符串str按组转换pattern的字符
for (int i = 0; i < p_len; ++i) {
bool flag = true;
for (int j = 0; j < i; ++j) {
if (strcmp(str + s_index[i], str + s_index[j]) == 0) {
s2p[i] = s2p[j];
flag = false;
break;
}
}
if (flag) {
if (k == count)
break;
s2p[i] = p[k++];
}
}
for (int i = 1; i < group; ++i) { // 恢复str为初始完整的字符串
str[s_index[i] - 1] = ' ';
}
for (int i = 0; i < p_len; ++i) { // 判断字符串是否匹配模式
if (s2p[i] != pattern[i])
return false;
}
return true;
}
ZigZag Conversion
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
char* convert(char* s, int numRows) {
int len = strlen(s);
if (len == 0 || numRows < 2)
return s;
char s_copy[len + 1];
strcpy(s_copy, s);
int stride = 2 * numRows - 2;
int count = 0;
for (int i = 0; i < numRows; ++i) {
bool flag = true; // 判断列的奇偶性
for (int j = i; j < len; ) {
s[count++] = s_copy[j];
if (i == 0 || i == numRows - 1) {
j += stride;
} else {
if (flag) {
j += stride - 2 * i;
flag = false;
} else {
j += 2 * i;
flag = true;
}
}
}
}
return s;
}
Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
int reverse(int x) {
if (x == INT_MIN || x == INT_MAX)
return 0;
bool is_positive = true;
long long result = 0;
if (x < 0) {
is_positive = false;
x = -x;
}
while (x != 0) {
result = result * 10 + x % 10;
if (result > INT_MAX || -result < INT_MIN) {
return 0;
}
x /= 10;
}
if (!is_positive)
result = -result;
return result;
}
String to Integer (atoi)
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
spoilers alert… click to show requirements for atoi.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
int myAtoi(char* str) {
if (str == NULL || *str == '\0')
return 0;
char* s = str;
bool is_positive = true;
bool find_num = false;
long long result = 0;
while (*s) {
if (*s < 33 || *s > 126) {
if (find_num)
break;
} else if (*s == '-' || *s == '+') {
if (find_num)
break;
is_positive = (*s == '+');
find_num = true;
} else if (*s >= '0' && *s <= '9') {
find_num = true;
if (find_num)
result = result * 10 + (*s - '0');
if (result > INT_MAX || -result < INT_MIN) {
if (is_positive)
return INT_MAX;
else
return INT_MIN;
}
} else {
break;
}
++s;
}
if (!is_positive)
result = -result;
return result;
}
Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
bool isPalindrome(int x) {
if (x < 0)
return false;
int x_copy = x;
long long result = 0;
while (x != 0) {
result = result * 10 + x % 10;
if (result > INT_MAX)
return false;
x /= 10;
}
if (x_copy == result)
return true;
else
return false;
}