文章目录
- #7.反转整数
- #9.回文数
- #13.罗马数字转整数
- #14.最长公共前缀
- 17.电话号码的字母组合
- #21.合并两个有序链表
- #23.合并K个排序链表
- #28.实现strStr()
- #35.搜索插入位置
- #36.有效的数独
- #38.报数
- #50.Pow(x, n)
- #53.最大子序和
- #58.最后一个单词的长度
- #63.不同路径 II
- #66.加一
- #67.二进制求和
- #69.x 的平方根
- #70.爬楼梯
- #83.删除排序链表中的重复元素
- #84.柱状图中最大的矩形
- #85.最大矩形
- #93.复原IP地址
- #98.验证二叉搜索树
- #100.相同的树
- #101.对称二叉树
- #104.二叉树的最大深度
- #108.将有序数组转换为二叉搜索树
- #110.平衡二叉树
- #111.二叉树的最小深度
- #112.路径总和
- #113.路径总和 II
- #118.杨辉三角
- #119.杨辉三角 II
- #121.买卖股票的最佳时机
- #122.买卖股票的最佳时机 II
- #127.单词接龙
- #129.求根到叶子节点数字之和
- #136.只出现一次的数字
- #141.环形链表
- #155.最小栈
- #160.相交链表
- #168.Excel表列名称
- #169.求众数
- #171.Excel表列序号
- #172.阶乘后的零
- #189.旋转数组
- #190.颠倒二进制位
- #191.位1的个数
- #204.计数质数
- #208. 实现 Trie (前缀树)
- #211. 添加与搜索单词 - 数据结构设计
- #222.完全二叉树的节点个数
- #225.用队列实现栈
- #226.翻转二叉树
- #230.二叉搜索树中第K小的元素
- #231. 2的幂
- #232.用栈实现队列
- #235.二叉搜索树的最近公共祖先
- #236.二叉树的最近公共祖先
- #257.二叉树的所有路径
- #258.各位相加
- #263.丑数
- #268.缺失数字
- #278.第一个错误的版本
- #279.完全平方数
- #292.Nim游戏
- #303.区域和检索 - 数组不可变
- #326. 3的幂
- #342. 4的幂
- #347.前K个高频元素
- #367.有效的完全平方数
- #371.两整数之和
- #374.猜数字大小
- #383.赎金信
- #387.字符串中的第一个唯一字符
- #389.找不同
- #404.左叶子之和
- #409.最长回文串
- #412.Fizz Buzz
- #415.字符串相加
- #429.N叉树的层序遍历
- #437.路径总和 III
- #450.删除二叉搜索树中的节点
- #461.汉明距离
- #476.数字的补数
- #500.键盘行
- #520.检测大写字母
- #557.反转字符串中的单词 III
- #677.键值映射
- #709.转换成小写字母
- #724.寻找数组的中心索引
- #728.自除数
- #747.至少是其他数字两倍的最大数
#7.反转整数
class Solution {
public:
int reverse(int x) {
string s = to_string(x);
std::reverse(s.begin(), s.end());
int res = 0;
try {
if (x < 0)
res = -stoi(s);
else
res = stoi(s);
} catch (exception e) {
return 0;
}
return res;
}
};
#9.回文数
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
string s = to_string(x);
size_t len = s.size();
size_t i = 0, j = len - 1;
while (i < j) {
if (s[i++] != s[j--]) return false;
}
return true;
}
};
#13.罗马数字转整数
class Solution {
private:
unordered_map<int, int> ROMAN;
public:
Solution() {
ROMAN['I'] = 1;
ROMAN['V'] = 5;
ROMAN['X'] = 10;
ROMAN['L'] = 50;
ROMAN['C'] = 100;
ROMAN['D'] = 500;
ROMAN['M'] = 1000;
}
int romanToInt(string s) {
int num = 0;
for (int i = 0; i < s.size(); ++i) {
switch (s[i]) {
case 'I':
if (i + 1 < s.size()) {
if (s[i + 1] == 'V') {
num += 4;
i++;
} else if (s[i + 1] == 'X') {
num += 9;
i++;
} else {
num += 1;
}
} else {
num += 1;
}
break;
case 'X':
if (i + 1 < s.size()) {
if (s[i + 1] == 'L') {
num += 40;
i++;
} else if (s[i + 1] == 'C') {
num += 90;
i++;
} else {
num += 10;
}
} else {
num += 10;
}
break;
case 'C':
if (i + 1 < s.size()) {
if (s[i + 1] == 'D') {
num += 400;
i++;
} else if (s[i + 1] == 'M') {
num += 900;
i++;
} else {
num += 100;
}
} else {
num += 100;
}
break;
default:
num += ROMAN[s[i]];
break;
}
}
return num;
}
};
#14.最长公共前缀
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
if (strs.size() == 0) return "";
if (strs.size() == 1) return strs[0];
string prefix = "";
for (int i = 0; i < strs[0].size(); ++i) {
int c = strs[0][i];
bool yes = true;
for (int j = 1; j < strs.size(); ++j)
if (strs[j][i] != c) {
yes = false;
break;
}
if (yes)
prefix += c;
else
break;
}
return prefix;
}
};
17.电话号码的字母组合
class Solution {
private:
vector<string> res;
string letter[10] = {
"", // 0
"", // 1
"abc", // 2
"def", // 3
"ghi", // 4
"jkl", // 5
"mno", // 6
"pqrs", // 7
"tuv", // 8
"wxyz" //9
};
void findCombinations(const string &digits, int index, const string &s) {
if (index == digits.size()) {
res.push_back(s);
return;
}
char c = digits[index];
string letters = letter[c - '0'];
for (int i = 0; i < letters.size(); ++i)
findCombinations(digits, index + 1, s + letters[i]);
}
public:
vector<string> letterCombinations(string digits) {
if (digits == "")
return res;
findCombinations(digits, 0, "");
return res;
}
};
#21.合并两个有序链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (!l1)return l2;
if (!l2) return l1;
ListNode *dummyHead1 = new ListNode(-1);
dummyHead1->next = l1;
ListNode *dummyHead2 = new ListNode(-1);
dummyHead2->next = l2;
ListNode *p1 = l1;
ListNode *p2 = l2;
ListNode *p = dummyHead1;
while (p1 && p2) {
if (p1->val < p2->val) {
p->next = p1;
p = p1;
p1 = p1->next;
} else {
p->next = p2;
p = p2;
p2 = p2->next;
}
}
if (p1)
p->next = p1;
if (p2)
p->next = p2;
return dummyHead1->next;
}
};
#23.合并K个排序链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
bool compare(ListNode *p1, ListNode *p2) {
return p1->val > p2->val;
}
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if (lists.size() == 0) return NULL;
priority_queue<ListNode *, vector<ListNode *>, function<bool(ListNode *, ListNode *)>> pq(compare);
for (int i = 0; i < lists.size(); ++i)
if (lists[i])
pq.push(lists[i]);
ListNode *dummyHead = new ListNode(0);
ListNode *p = dummyHead;
while (!pq.empty()) {
ListNode *node = pq.top();
pq.pop();
p->next = node;
p = node;
if (node->next)
pq.push(node->next);
}
p->next = NULL;
ListNode *head = dummyHead->next;
delete dummyHead;
return head;
}
};
#28.实现strStr()
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.size() == 0)return 0;
if (needle.size() > haystack.size())return -1;
int j = 0;
for (int i = 0; i < haystack.size(); ++i) {
if (haystack[i] == needle[j]) {
j++;
if (j >= needle.size())
return (int) (i - needle.size() + 1);
} else {
i = i - j; // 回溯,如 mississippi , issip
j = 0;
}
}
return -1;
}
};
#35.搜索插入位置
class Solution {
public:
int searchInsert(vector<int> &nums, int target) {
int size = (int) nums.size();
for (int i = 0; i < size; ++i) {
if (nums[i] >= target) {
return i;
}
}
return size;
}
};
#36.有效的数独
class Solution {
private:
vector<vector<bool>> row;
vector<vector<bool>> col;
vector<vector<bool>> grid;
public:
bool isValidSudoku(vector<vector<char>> &board) {
row = vector<vector<bool>>(9, vector<bool>(9, false));
col = vector<vector<bool>>(9, vector<bool>(9, false));
grid = vector<vector<bool>>(9, vector<bool>(9, false));
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 9; ++j) {
char c = board[i][j];
if (c != '.') {
int num = c - '1';
if (!row[i][num])
row[i][num] = true;
else
return false;
if (!col[j][num])
col[j][num] = true;
else
return false;
if (!grid[i / 3 * 3 + j / 3][num])
grid[i / 3 * 3 + j / 3][num] = true;
else
return false;
}
}
return true;
}
};
#38.报数
class Solution {
public:
string countAndSay(int n) {
vector<string> SEQ;
SEQ.push_back("0");
SEQ.push_back("1");
string curSeq = SEQ[1];
for (int i = 2; i <= n; ++i) {
string tmp;
int count = 1;
char curNum = curSeq[0];
for (int j = 1; j < curSeq.size(); ++j)
if (curSeq[j] == curNum)
count++;
else {
tmp += to_string(count);
tmp += curNum;
count = 1;
curNum = curSeq[j];
}
tmp += to_string(count);
tmp += curNum;
SEQ.push_back(tmp);
curSeq = SEQ[i];
}
return SEQ[n];
}
};
#50.Pow(x, n)
class Solution {
public:
double myPow(double x, int n) {
if (n > 0)
return pow(x, n);
else
return 1.0 / pow(x, abs(n));
}
double pow(double x, int n) {
if (n == 0)
return 1.0;
if (n == 1)
return x;
double val = pow(x, n / 2);
if (n % 2 == 0)
return val * val;
else
return val * val * x;
}
};
#53.最大子序和
class Solution {
public:
int maxSubArray(vector<int> &nums) {
int thisSum = 0;
int maxSum = 0;
bool isAllNegative = true;
int maxValue = nums[0];
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] > 0) isAllNegative = false;
if (nums[i] > maxValue)maxValue = nums[i];
thisSum += nums[i];
if (thisSum > maxSum)
maxSum = thisSum;
else if (thisSum < 0)
thisSum = 0;
}
if (isAllNegative)
return maxValue;
else
return maxSum;
}
};
#58.最后一个单词的长度
class Solution {
public:
int lengthOfLastWord(string s) {
if (s.size() == 0) return 0;
int r;
for (r = (int) (s.size() - 1); r >= 0; --r)
if (s[r] != ' ')
break;
int l;
for (l = r - 1; l >= 0; --l)
if (s[l] == ' ') {
l += 1;
break;
}
if (l < 0)
l = 0;
return r - l + 1;
}
};
#63.不同路径 II
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
int m = obstacleGrid.size();
if (m == 0)
return 0;
int n = obstacleGrid[0].size();
vector<vector<int>> memo = vector<vector<int>>(m, vector<int>(n, -1));
int k;
for (k = 0; k < m && obstacleGrid[k][0] != 1; ++k)
memo[k][0] = 1;
while (k < m)
memo[k++][0] = 0;
for (k = 0; k < n && obstacleGrid[0][k] != 1; ++k)
memo[0][k] = 1;
while (k < n)
memo[0][k++] = 0;
for (int i = 1; i < m; ++i)
for (int j = 1; j < n; ++j)
if (obstacleGrid[i][j] == 1)
memo[i][j] = 0;
else
memo[i][j] = memo[i - 1][j] + memo[i][j - 1];
return memo[m - 1][n - 1];
}
};
#66.加一
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int carry = 1;
for (int i = (int) (digits.size() - 1); i >= 0; --i) {
digits[i] += carry;
if (digits[i] >= 10) {
digits[i] %= 10;
carry = 1;
} else
carry = 0;
}
if (carry)
digits.insert(digits.begin(), 1);
return digits;
}
};
#67.二进制求和
class Solution {
public:
string addBinary(string a, string b) {
if (a.size() < b.size()) {
string tmp = a;
a = b;
b = tmp;
}
int carry = 0;
int j = (int) (b.size() - 1);
for (int i = (int) (a.size() - 1); i >= 0; --i) {
int digit;
if (j < 0)
digit = c2i(a[i]) + carry;
else
digit = c2i(a[i]) + c2i(b[j--]) + carry;
if (digit >= 2) {
digit %= 2;
carry = 1;
} else {
carry = 0;
}
a[i] = i2c(digit);
}
if (carry)
a.insert(a.begin(), '1');
return a;
}
int c2i(char c) {
return c - '0';
}
char i2c(int x) {
return (char) (x + '0');
}
};
#69.x 的平方根
class Solution {
public:
int mySqrt(int x) {
if (x <= 1) return x;
int low = 0, high = x;
while (low <= high) {
int mid = (low + high) / 2;
if (mid <= x / mid && (mid + 1) > x / (mid + 1)) {
return mid;
} else if (mid > x / mid) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return 0;
}
};
#70.爬楼梯
class Solution {
private:
unordered_map<int, int> STAIR;
public:
Solution() {
STAIR[1] = 1;
STAIR[2] = 2;
}
int climbStairs(int n) {
if (STAIR.find(n) != STAIR.end())
return STAIR[n];
else
return STAIR[n] = climbStairs(n - 1) + climbStairs(n - 2);
}
};
#83.删除排序链表中的重复元素
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if (head == NULL || head->next == NULL) return head;
ListNode *pre = head;
ListNode *p = head->next;
while (p) {
if (p->val == pre->val) {
ListNode *delNode = p;
pre->next = p->next;
p = p->next;
delete delNode;
} else {
pre = p;
p = p->next;
}
}
return head;
}
};
#84.柱状图中最大的矩形
typedef struct Rect{
int height, pos;
Rect(int height, int pos):height(height), pos(pos){}
}Rect;
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<Rect> S;
int res = 0;
heights.push_back(0);
for(int i=0;i<heights.size();i++){
Rect rect(heights[i], i);
if(S.empty() || S.top().height < rect.height){
S.push(rect);
}else if(S.top().height > rect.height){
int pos = i;
while(!S.empty() && S.top().height >= rect.height){
Rect top = S.top();
S.pop();
int area = top.height * (i - top.pos);
res = max(res, area);
pos = top.pos;
}
rect.pos = pos;
S.push(rect);
}
}
return res;
}
};
#85.最大矩形
typedef struct Rect{
int height, pos;
Rect(int height, int pos):height(height), pos(pos){}
}Rect;
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
vector<vector<int>> T;
for(int i=0;i<matrix.size();i++){
vector<int> line;
for(int j=0;j<matrix[i].size();j++){
if(matrix[i][j] == '0'){
line.push_back(0);
}else{
if(i>=1)
line.push_back(T[i-1][j] + 1);
else
line.push_back(1);
}
}
T.push_back(line);
}
int maxv = 0;
for(int i = 0;i<T.size();i++){
vector<int> line = T[i];
line.push_back(0);
stack<Rect> S;
for(int j = 0;j<line.size();j++){
Rect rect(line[j], j);
if(S.empty() || S.top().height < rect.height){
S.push(rect);
}else if(S.top().height > rect.height){
int pos = j;
while(!S.empty() && S.top().height >= rect.height){
Rect top = S.top();
S.pop();
int area = top.height * (j - top.pos);
maxv = max(maxv, area);
pos = top.pos;
}
rect.pos = pos;
S.push(rect);
}
}
}
return maxv;
}
};
#93.复原IP地址
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
if (s.size() < 4 || s.size() > 12)
return res;
int i, j, k;
for (i = 0; i <= s.size() - 4; ++i)
for (j = i + 1; j <= s.size() - 3; ++j)
for (k = j + 1; k <= s.size() - 2; ++k) {
string first = s.substr(0, i + 1);
string second = s.substr(i + 1, j - i);
string third = s.substr(j + 1, k - j);
string fourth = s.substr(k + 1, s.size() - 1 - k);
if (first.size() > 3 || second.size() > 3 || third.size() > 3 || fourth.size() > 3)
continue;
if (first.size() > 1 && first[0] == '0' ||
second.size() > 1 && second[0] == '0' ||
third.size() > 1 && third[0] == '0' ||
fourth.size() > 1 && fourth[0] == '0')
continue;
if (stol(first) <= 255 &&
stol(second) <= 255 &&
stol(third) <= 255 &&
stol(fourth) <= 255) {
string ans = first + "." + second + "." + third + "." + fourth;
res.push_back(ans);
}
}
return res;
}
};
#98.验证二叉搜索树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
return isBST(root, LONG_MIN, LONG_MAX);
}
bool isBST(TreeNode *root, long lower, long upper) {
if (root == NULL)
return true;
if (root->val <= lower || root->val >= upper)
return false;
return isBST(root->left, lower, root->val) && isBST(root->right, root->val, upper);
}
};
#100.相同的树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if (p && q)
return p->val == q->val &&
isSameTree(p->left, q->left) &&
isSameTree(p->right, q->right);
else
return !p && !q;
}
};
#101.对称二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode *root) {
if (root == NULL)return true;
return symmetric(root->left, root->right);
}
bool symmetric(TreeNode *p, TreeNode *q) {
if (p && q)
return p->val == q->val &&
symmetric(p->right, q->left) &&
symmetric(p->left, q->right);
else
return !(p || q);
}
};
#104.二叉树的最大深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
if (root == NULL)
return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
#108.将有序数组转换为二叉搜索树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &nums) {
if (nums.size() == 0)
return NULL;
return sortedArrayToBST(nums, 0, (int) nums.size() - 1);
}
private:
TreeNode *sortedArrayToBST(vector<int> &nums, int begin, int end) {
if (begin > end)
return NULL;
if (begin == end)
return new TreeNode(nums[begin]);
int mid = (begin + end) / 2;
TreeNode *root = new TreeNode(nums[mid]);
root->left = sortedArrayToBST(nums, begin, mid - 1);
root->right = sortedArrayToBST(nums, mid + 1, end);
return root;
}
};
#110.平衡二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
if (root == NULL)
return true;
int leftHeight = depth(root->left);
int rightHeight = depth(root->right);
return abs(leftHeight - rightHeight) <= 1 &&
isBalanced(root->left) &&
isBalanced(root->right);
}
int depth(TreeNode *root) {
if (root == NULL)
return 0;
return max(depth(root->left), depth(root->right)) + 1;
}
};
#111.二叉树的最小深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode *root) {
if (root == NULL)
return 0;
if (root->left && root->right)
return min(minDepth(root->left), minDepth(root->right)) + 1;
if (root->left)
return minDepth(root->left) + 1;
if (root->right)
return minDepth(root->right) + 1;
return 1;
}
};
#112.路径总和
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if (root == NULL)
return false;
if (!root->left && !root->right && root->val == sum)
return true;
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};
#113.路径总和 II
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode *root, int sum) {
vector<vector<int>> res;
if (root == NULL)
return res;
if (root->left == NULL && root->right == NULL)
if (root->val == sum)
res.push_back(vector<int>{root->val});
else
return res;
vector<vector<int>> leftPath = pathSum(root->left, sum - root->val);
for (int i = 0; i < leftPath.size(); ++i) {
leftPath[i].insert(leftPath[i].begin(), root->val);
res.push_back(leftPath[i]);
}
vector<vector<int>> rightPath = pathSum(root->right, sum - root->val);
for (int i = 0; i < rightPath.size(); ++i) {
rightPath[i].insert(rightPath[i].begin(), root->val);
res.push_back(rightPath[i]);
}
return res;
}
};
#118.杨辉三角
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
if (numRows == 0)return res;
res.push_back(vector<int>{1});
for (int i = 1; i <= numRows - 1; ++i) { // i对应行
vector<int> row;
for (int j = 0; j <= i; ++j) {
int left = j - 1 < 0 ? 0 : res[i - 1][j - 1];
int right = j >= res[i - 1].size() ? 0 : res[i - 1][j];
row.push_back(left + right);
}
res.push_back(row);
}
return res;
}
};
#119.杨辉三角 II
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res;
res.push_back(1);
for (int i = 1; i <= rowIndex; ++i) {
res.push_back(0);
for (int j = i; j > 0; --j)
res[j] += res[j - 1];
res[0] = 1;
}
return res;
}
};
#121.买卖股票的最佳时机
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() == 0)return 0;
int min = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.size(); ++i) {
int profit = prices[i] - min;
if (profit > maxProfit)
maxProfit = profit;
if (prices[i] < min)
min = prices[i];
}
return maxProfit;
}
};
#122.买卖股票的最佳时机 II
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0)
return 0;
int sum = 0;
for(int i = 0;i < prices.size()-1; i++)
if(prices[i] < prices[i+1])
sum += prices[i+1] - prices[i];
return sum;
}
};
#127.单词接龙
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string> &wordList) {
bool possible = false;
for (int i = 0; i < wordList.size(); ++i)
if (endWord == wordList[i]) {
possible = true;
break;
}
// endWord不在列表中
if (!possible)
return 0;
queue<pair<string, int>> q;
q.push(make_pair(beginWord, 1));
vector<bool> visited(wordList.size(), false);
while (!q.empty()) {
string word = q.front().first;
int step = q.front().second;
q.pop();
for (int i = 0; i < wordList.size(); ++i) {
string item = wordList[i];
if (!visited[i] && isClose(word, item)) {
if (item == endWord)
return step + 1;
q.push(make_pair(item, step + 1));
visited[i] = true;
}
}
}
return 0;
}
bool isClose(string a, string b) {
int different = 0;
for (int i = 0; i < a.size() && different < 2; ++i)
if (a[i] != b[i])
different++;
return different == 1;
}
};
#129.求根到叶子节点数字之和
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode *root) {
vector<vector<int>> paths = getPath(root);
int res = 0;
for (auto &path:paths) {
int sum = 0;
for (int i = (int) path.size() - 1; i >= 0; --i)
sum += path[path.size() - 1 - i] * pow(10, i);
res += sum;
}
return res;
}
vector<vector<int>> getPath(TreeNode *root) {
vector<vector<int>> paths;
if (root == NULL)
return paths;
if (root->left == NULL && root->right == NULL)
paths.push_back(vector<int>{root->val});
vector<vector<int>> leftPaths = getPath(root->left);
for (int i = 0; i < leftPaths.size(); ++i) {
leftPaths[i].insert(leftPaths[i].begin(), root->val);
paths.push_back(leftPaths[i]);
}
vector<vector<int>> rightPaths = getPath(root->right);
for (int i = 0; i < rightPaths.size(); ++i) {
rightPaths[i].insert(rightPaths[i].begin(), root->val);
paths.push_back(rightPaths[i]);
}
return paths;
}
};
#136.只出现一次的数字
class Solution {
public:
int singleNumber(vector<int> &nums) {
int ans = 0;
for (int i = 0; i < nums.size(); ++i)
ans ^= nums[i];
return ans;
}
};
#141.环形链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL || head->next == NULL)
return false;
ListNode *fast = head->next;
ListNode *slow = head;
while (fast != slow) {
if (fast == NULL || fast->next == NULL)
return false;
fast = fast->next->next;
slow = slow->next;
}
return true;
}
};
#155.最小栈
class MinStack {
private:
stack<int> data;
stack<int> min;
public:
/** initialize your data structure here. */
MinStack() {
data = stack<int>();
min = stack<int>();
}
void push(int x) {
data.push(x);
if (min.empty() || x <= min.top())
min.push(x);
}
void pop() {
int val = data.top();
data.pop();
if (val == min.top())
min.pop();
}
int top() {
return data.top();
}
int getMin() {
return min.top();
}
};
#160.相交链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == nullptr || headB == nullptr)
return nullptr;
ListNode *pa = headA;
ListNode *pb = headB;
int lenA = 1, lenB = 1;
while (pa != nullptr) {
pa = pa->next;
lenA++;
}
while (pb != nullptr) {
pb = pb->next;
lenB++;
}
if (pa != pb)
return nullptr;
pa = headA;
pb = headB;
int distance = lenA - lenB;
if (distance > 0)
while (distance--)
pa = pa->next;
else
while (distance++)
pb = pb->next;
while (pa != pb) {
pa = pa->next;
pb = pb->next;
}
return pa;
}
};
#168.Excel表列名称
class Solution {
public:
string convertToTitle(int n) {
string res;
stringstream ss;
while (n) {
char c;
if (n % 26 == 0)
c = 'Z';
else
c = (char) (n % 26 - 1 + 'A');
ss.str("");
ss << c;
res = ss.str() + res;
if (n % 26 != 0)
n /= 26;
else
n = n / 26 - 1;
}
return res;
}
};
#169.求众数
class Solution {
public:
int majorityElement(vector<int> &nums) {
int majority = nums[0];
int count = 1;
for (int i = 1; i < nums.size(); ++i)
if (nums[i] == majority)
count++;
else {
count--;
if (count == 0) {
majority = nums[i];
count = 1;
}
}
return majority;
}
};
#171.Excel表列序号
class Solution {
public:
int titleToNumber(string s) {
int x = 0, y = 0;
int res = 0;
for (int i = 0; i < s.size(); ++i) {
y = s[i] - 'A' + 1;
res = x * 26 + y;
x = res;
}
return res;
}
};
#172.阶乘后的零
class Solution {
public:
int trailingZeroes(int n) {
int res = 0;
while (n)
res += n /= 5;
return res;
}
};
#189.旋转数组
class Solution {
public:
void rotate(vector<int> &nums, int k) {
k %= nums.size();
reverse(nums.begin(), nums.begin() + (nums.size() - k));
reverse(nums.begin() + (nums.size() - k), nums.end());
reverse(nums.begin(), nums.end());
}
};
#190.颠倒二进制位
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
vector<int> record = {};
while (n) {
int r = n % 2;
record.push_back(r);
n /= 2;
}
uint32_t res = 0;
int len = (int) record.size();
for (int j = 1; j <= 32 - len; ++j)
record.push_back(0);
for (int i = 0; i < 32; ++i)
res += record[i] * pof2(32 - i - 1);
return res;
}
uint32_t pof2(int power) {
uint32_t res = 1;
for (int i = 1; i <= power; ++i)
res *= 2;
return res;
}
};
#191.位1的个数
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while (n) {
if (n % 2)
res++;
n /= 2;
}
return res;
}
};
#204.计数质数
class Solution {
public:
int countPrimes(int n) {
bool *prime = new bool[n];
memset(prime, 1, n);
prime[0] = false;
prime[1] = false;
double sqt = sqrt(n);
for (int i = 2; i <= sqt; ++i)
if (prime[i] && isPrime(i))
for (int j = 2; j * i < n; ++j)
prime[j * i] = false;
int res = 0;
for (int k = 0; k < n; ++k)
if (prime[k])
res++;
return res;
}
bool isPrime(int n) {
if (n == 1)return false;
double k = sqrt(n);
for (int i = 2; i <= k; ++i)
if (n % i == 0)
return false;
return true;
}
};
#208. 实现 Trie (前缀树)
class Trie {
private:
typedef struct Node {
bool isWord;
unordered_map<char, Node *> children;
Node() : isWord(false) {}
} Node;
Node *root;
public:
/** Initialize your data structure here. */
Trie() {
root = new Node();
}
/** Inserts a word into the trie. */
void insert(string word) {
Node *cur = root;
for (char c: word) {
if (cur->children.find(c) == cur->children.end())
cur->children.insert(make_pair(c, new Node));
cur = cur->children[c];
}
cur->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Node *cur = root;
for (char c : word) {
if (cur->children.find(c) == cur->children.end())
return false;
cur = cur->children[c];
}
return cur->isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Node *cur = root;
for (char c : prefix) {
if (cur->children.find(c) == cur->children.end())
return false;
cur = cur->children[c];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* bool param_2 = obj.search(word);
* bool param_3 = obj.startsWith(prefix);
*/
#211. 添加与搜索单词 - 数据结构设计
class WordDictionary {
private:
typedef struct Node {
bool isWord;
unordered_map<char, Node *> children;
Node() : isWord(false) {}
} Node;
Node *root;
bool search(Node *node, string word, int index) {
if (index == word.size())
return node->isWord;
int c = word[index];
if (c != '.') {
if (node->children.find(c) == node->children.end())
return false;
return search(node->children[c], word, index + 1);
} else {
for (pair < char, Node * > child : node->children) {
char chr = child.first;
if (search(node->children[chr], word, index + 1))
return true;
}
return false;
}
}
public:
/** Initialize your data structure here. */
WordDictionary() {
root = new Node();
}
/** Adds a word into the data structure. */
void addWord(string word) {
Node *cur = root;
for (char c: word) {
if (cur->children.find(c) == cur->children.end())
cur->children.insert(make_pair(c, new Node));
cur = cur->children[c];
}
cur->isWord = true;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(string word) {
return search(root, word, 0);
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* bool param_2 = obj.search(word);
*/
#222.完全二叉树的节点个数
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode *root) {
if (root == NULL)
return 0;
int leftDepth = 0;
int rightDepth = 0;
TreeNode *p, *q;
p = root;
q = root;
while (p || q) {
if (p) {
leftDepth++;
p = p->left;
}
if (q) {
rightDepth++;
q = q->right;
}
}
if (leftDepth == rightDepth)
return (int) pow(2, leftDepth) - 1;
else
return countNodes(root->left) + countNodes(root->right) + 1;
}
};
#225.用队列实现栈
class MyStack {
private:
queue<int> first;
queue<int> second;
public:
/** Initialize your data structure here. */
MyStack() {
first = queue<int>();
second = queue<int>();
}
/** Push element x onto stack. */
void push(int x) {
first.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
while (first.size() != 1) {
int val = first.front();
first.pop();
second.push(val);
}
int ret = first.front();
first.pop();
while (!second.empty()) {
int val = second.front();
second.pop();
first.push(val);
}
return ret;
}
/** Get the top element. */
int top() {
return first.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return first.empty();
}
};
#226.翻转二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *invertTree(TreeNode *root) {
if (root == NULL)
return root;
TreeNode *tmp = root->left;
root->left = root->right;
root->right = tmp;
invertTree(root->left);
invertTree(root->right);
return root;
}
};
#230.二叉搜索树中第K小的元素
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int k;
int count;
int res;
public:
int kthSmallest(TreeNode *root, int k) {
this->k = k;
this->count = 0;
this->res = 0;
inorder(root);
return res;
}
void inorder(TreeNode *root) {
if (root) {
inorder(root->left);
this->count++;
if (this->count == k) {
this->res = root->val;
return;
}
inorder(root->right);
}
}
};
#231. 2的幂
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n % 2 == 1 && n != 1)
return false;
while (n && n % 2 == 0)
n /= 2;
return n == 1;
}
};
#232.用栈实现队列
class MyQueue {
private:
stack<int> first;
stack<int> second;
public:
/** Initialize your data structure here. */
MyQueue() {
first = stack<int>();
second = stack<int>();
}
/** Push element x to the back of queue. */
void push(int x) {
first.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if (!second.empty()) {
int top = second.top();
second.pop();
return top;
}
while (!first.empty()) {
int top = first.top();
second.push(top);
first.pop();
}
int top = second.top();
second.pop();
return top;
}
/** Get the front element. */
int peek() {
if (!second.empty())
return second.top();
while (!first.empty()) {
int top = first.top();
second.push(top);
first.pop();
}
return second.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return first.empty() && second.empty();
}
};
#235.二叉搜索树的最近公共祖先
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
if (root == NULL)
return nullptr;
if (p->val < root->val && q->val < root->val)
return lowestCommonAncestor(root->left, p, q);
if (p->val > root->val && q->val > root->val)
return lowestCommonAncestor(root->right, p, q);
return root;
}
};
#236.二叉树的最近公共祖先
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL || root == p || root == q)
return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if(left && right)
return root;
return left ?: right;
}
};
#257.二叉树的所有路径
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode *root) {
vector<string> res;
if (root == NULL)
return res;
if (!root->left && !root->right) {
res.push_back(to_string(root->val));
return res;
}
vector<string> leftStrs = binaryTreePaths(root->left);
for (int i = 0; i < leftStrs.size(); ++i)
res.push_back(to_string(root->val) + "->" + leftStrs[i]);
vector<string> rightStrs = binaryTreePaths(root->right);
for (int i = 0; i < rightStrs.size(); ++i)
res.push_back(to_string(root->val) + "->" + rightStrs[i]);
return res;
}
};
#258.各位相加
class Solution {
public:
int addDigits(int num) {
return (num - 1) % 9 + 1;
}
};
#263.丑数
class Solution {
public:
bool isUgly(int num) {
if (num == 1)return true;
if (num == 0) return false;
while (num != 2 && num != 3 && num != 5) {
if (num % 2 == 0)
num /= 2;
else if (num % 3 == 0)
num /= 3;
else if (num % 5 == 0)
num /= 5;
else
return false;
}
return true;
}
};
#268.缺失数字
class Solution {
public:
int missingNumber(vector<int> &nums) {
int res = 0;
int n = (int) nums.size();
for (int i = 0; i < n; ++i) {
res += i;
res -= nums[i];
}
res += n;
return res;
}
};
#278.第一个错误的版本
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int low = 1, high = n;
while (low <= high) {
if (isBadVersion(low))
return low;
int mid = low + (high - low) / 2;
if (isBadVersion(mid))
if (!isBadVersion(mid - 1))
return mid;
else
high = mid;
else
low = mid + 1;
}
return n;
}
};
#279.完全平方数
class Solution {
public:
int numSquares(int n) {
while (n % 4 == 0)
n /= 4;
if (n % 8 == 7)return 4;
for (int a = 0; a * a < n; ++a) {
int b = (int) sqrt(n - a * a);
if (a * a + b * b == n)
return (a != 0) + (b != 0);
}
return 3;
}
};
解法二:
class Solution {
public:
int numSquares(int n) {
assert(n > 0);
queue<pair<int, int>> q;
q.push(make_pair(n, 0));
vector<bool> visited((unsigned) (n + 1), false);
visited[n] = true;
while (!q.empty()) {
int num = q.front().first;
int step = q.front().second;
q.pop();
for (int i = 1;; ++i) {
int a = num - i * i;
if (a < 0)
break;
if (a == 0)
return step + 1;
if (!visited[a]) {
q.push(make_pair(a, step + 1));
visited[a] = true;
}
}
}
throw invalid_argument("No Solution");
}
};
#292.Nim游戏
class Solution {
public:
bool canWinNim(int n) {
return n % 4 != 0;
}
};
#303.区域和检索 - 数组不可变
class NumArray {
private:
vector<int> con;
vector<int> memo;
public:
NumArray(vector<int> nums) {
con = nums;
int n = nums.size();
memo = vector<int>(n + 1, 0);
memo[0] = 0;
for (int i = 0; i < n; ++i)
memo[i + 1] = con[i] + memo[i];
}
int sumRange(int i, int j) {
return memo[j + 1] - memo[i];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
#326. 3的幂
class Solution {
public:
bool isPowerOfThree(int n) {
if (n == 0)
return false;
while (n != 1) {
if (n % 3 != 0)
return false;
n /= 3;
}
return true;
}
};
#342. 4的幂
class Solution {
public:
bool isPowerOfFour(int num) {
if (num == 0)
return false;
while (num != 1) {
if (num % 4 != 0)
return false;
num /= 4;
}
return true;
}
};
#347.前K个高频元素
class Solution {
public:
vector<int> topKFrequent(vector<int> &nums, int k) {
// <数据, 频率>
unordered_map<int, int> freq;
for (int i = 0; i < nums.size(); ++i)
freq[nums[i]]++;
// pair<int, int> 对应<频率, 数据>
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
for (auto &record: freq) {
if (pq.size() == k) {
if (record.second > pq.top().first) {
pq.pop();
pq.push(make_pair(record.second, record.first));
}
} else {
pq.push(make_pair(record.second, record.first));
}
}
vector<int> res;
while (!pq.empty()) {
res.push_back(pq.top().second);
pq.pop();
}
return res;
}
};
#367.有效的完全平方数
class Solution {
public:
bool isPerfectSquare(int num) {
if (num == 1)
return true;
int low = 1;
int high = num / 2;
while (low <= high) {
unsigned long mid = low + (high - low) / 2;
unsigned long t = mid * mid;
if (t == num)
return true;
else if (t > num)
high = mid - 1;
else
low = mid + 1;
}
return false;
}
};
#371.两整数之和
class Solution {
public:
int getSum(int a, int b) {
if (a == 0)return b;
if (b == 0)return a;
int xhr = a ^b;
int carry = (a & b) << 1;
return getSum(xhr, carry);
}
};
#374.猜数字大小
// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);
class Solution {
public:
int guessNumber(int n) {
int low = 1;
int high = n;
while (low <= high) {
int mid = low + (high - low) / 2;
int t = guess(mid);
if (t == 0) {
return mid;
} else if (t < 0) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return 1;
}
};
#383.赎金信
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int m = (int) ransomNote.size();
int n = (int) magazine.size();
unordered_map<int, int> ransomNoteMap;
unordered_map<int, int> magazineMap;
for (int i = 0; i < m; ++i)
ransomNoteMap[ransomNote[i]]++;
for (int i = 0; i < n; ++i)
magazineMap[magazine[i]]++;
for (unordered_map<int, int>::iterator iter = ransomNoteMap.begin(); iter != ransomNoteMap.end(); iter++) {
if (magazineMap.find((*iter).first) == magazineMap.end() || magazineMap[(*iter).first] < (*iter).second)
return false;
}
return true;
}
};
#387.字符串中的第一个唯一字符
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<int, int> record;
for (char c:s)
record[c]++;
for (int i = 0; i < s.size(); ++i) {
char c = s[i];
if (record[c] == 1)
return i;
}
return -1;
}
};
#389.找不同
class Solution {
public:
char findTheDifference(string s, string t) {
s += t;
char c = s[0];
for (int i = 1; i < s.size(); ++i) {
c ^= s[i];
}
return c;
}
};
#404.左叶子之和
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode *root) {
if (root == NULL)
return 0;
if (isLeaf(root->left))
return root->left->val + sumOfLeftLeaves(root->right);
else
return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
bool isLeaf(TreeNode *node) {
if (node == NULL)
return false;
return !node->left && !node->right;
}
};
#409.最长回文串
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> record;
for (int i = 0; i < s.size(); ++i)
record[s[i]]++;
int res = 0;
for (auto &item: record)
if (item.second % 2 == 0)
res += item.second;
else
res += item.second - 1;
return res < s.size() ? res + 1 : res;
}
};
#412.Fizz Buzz
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> res;
if (n == 0)
return res;
for (int i = 1; i <= n; ++i) {
string s;
if (i % 15 == 0)
s = "FizzBuzz";
else if (i % 3 == 0)
s = "Fizz";
else if (i % 5 == 0)
s = "Buzz";
else
s = to_string(i);
res.push_back(s);
}
return res;
}
};
#415.字符串相加
class Solution {
public:
string addStrings(string num1, string num2) {
if (num1.size() < num2.size())
swap(num1, num2);
int j = (int) (num2.size() - 1);
int carry = 0;
for (int i = (int) (num1.size() - 1); i >= 0; --i) {
int v1 = num1[i] - '0';
int v2 = j >= 0 ? (num2[j] - '0') : 0;
int digit = v1 + v2 + carry;
if (digit >= 10)
carry = 1;
else
carry = 0;
num1[i] = (char) (digit % 10 + '0');
--j;
}
if (carry == 1)
num1.insert(num1.begin(), '1');
return num1;
}
};
#429.N叉树的层序遍历
/*
// Definition for a Node.
class Node {
public:
int val = NULL;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<vector<int>> levelOrder(Node *root) {
vector<vector<int>> res;
if (root == NULL)
return res;
queue<pair<Node *, int>> queue;
queue.push(make_pair(root, 0));
while (!queue.empty()) {
Node *node = queue.front().first;
int level = queue.front().second;
queue.pop();
if (res.size() == level) {
res.push_back(vector<int>());
}
res[level].push_back(node->val);
if (node->children.size() != 0) {
for (int i = 0; i < node->children.size(); ++i) {
queue.push(make_pair(node->children[i], level + 1));
}
}
}
return res;
}
};
#437.路径总和 III
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// 在以root为根节点的二叉树中,寻找和为sum的路径,返回这样路径个数
int pathSum(TreeNode *root, int sum) {
if (root == NULL)
return 0;
int res = findPath(root, sum);
res += pathSum(root->left, sum);
res += pathSum(root->right, sum);
return res;
}
private:
// 在以node为根节点的二叉树中,寻找包含node的路径,和为sum
// 返回这样的路径个数
int findPath(TreeNode *node, int sum) {
if (node == NULL)
return 0;
int res = 0;
if (node->val == sum)
res += 1;
res += findPath(node->left, sum - node->val);
res += findPath(node->right, sum - node->val);
return res;
}
};
#450.删除二叉搜索树中的节点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *deleteNode(TreeNode *root, int key) {
if (root == NULL)
return NULL;
if (key < root->val) {
root->left = deleteNode(root->left, key);
return root;
} else if (key > root->val) {
root->right = deleteNode(root->right, key);
return root;
} else {
if (root->left == NULL) {
TreeNode *rightNode = root->right;
delete root;
return rightNode;
}
if (root->right == NULL) {
TreeNode *leftNode = root->left;
delete root;
return leftNode;
}
TreeNode *successor = new TreeNode(minimum(root->right)->val);
successor->right = deleteMinNode(root->right);
successor->left = root->left;
delete root;
return successor;
}
}
TreeNode *minimum(TreeNode *root) {
if (root == NULL || root->left == NULL)
return root;
return minimum(root->left);
}
TreeNode *deleteMinNode(TreeNode *root) {
if (root == NULL)
return NULL;
if (root->left == NULL) {
TreeNode *rightNode = root->right;
delete root;
return rightNode;
}
root->left = deleteMinNode(root->left);
return root;
}
};
#461.汉明距离
class Solution {
public:
int hammingDistance(int x, int y) {
int r = x^y;
int res = 0;
while(r){
if(r%2){
res++;
}
r /= 2;
}
return res;
}
};
#476.数字的补数
class Solution {
public:
int findComplement(int num) {
stack<int> record;
while (num) {
int rest = num % 2;
record.push(rest);
num /= 2;
}
int res = 0;
while (!record.empty()) {
int power = (int) (record.size() - 1);
int digit = record.top();
digit = digit ? 0 : 1;
res += digit * powerof2(power);
record.pop();
}
return res;
}
int powerof2(int power) {
int res = 1;
while (power--)
res *= 2;
return res;
}
};
#500.键盘行
class Solution {
public:
vector<string> findWords(vector<string> &words) {
vector<string> alphabet = {"QWERTYUIOPqwertyuiop", "ASDFGHJKLasdfghjkl", "ZXCVBNMzxcvbnm"};
unordered_map<int, int> record;
for (int i = 0; i < alphabet.size(); ++i) {
string line = alphabet[i];
for (int j = 0; j < line.size(); ++j)
record[line[j]] = i;
}
vector<string> res;
for (int i = 0; i < words.size(); ++i) {
string word = words[i];
int order = record[word[0]];
bool oneline = true;
for (int j = 1; j < word.size(); ++j)
if (record[word[j]] != order) {
oneline = false;
break;
}
if (oneline)
res.push_back(word);
}
return res;
}
};
#520.检测大写字母
class Solution {
private:
bool isCapital(char c) {
return c >= 'A' && c <= 'Z';
}
public:
bool detectCapitalUse(string word) {
if (word.size() == 1)
return true;
if (!isCapital(word[0])) {
for (int i = 1; i < word.size(); i++)
if (isCapital(word[i]))
return false;
return true;
} else {
if (isCapital(word[1])) {
for (int i = 2; i < word.size(); i++)
if (!isCapital(word[i]))
return false;
return true;
} else {
for (int i = 2; i < word.size(); i++)
if (isCapital(word[i]))
return false;
return true;
}
}
}
};
#557.反转字符串中的单词 III
class Solution {
public:
string reverseWords(string s) {
int begin = 0;
int end = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == ' ' || i == s.size() - 1) {
if (i == s.size() - 1)
end = s.size();
else
end = i;
reverse(&s[begin], &s[end]);
if (i != s.size() - 1)
begin = end + 1;
}
}
return s;
}
};
#677.键值映射
class MapSum {
private:
typedef struct Node {
int value;
map<char, Node *> children;
Node() : value(0) {}
Node(int value) : value(value) {}
} Node;
int sum(Node *node) {
int res = node->value;
for (pair<char, Node *> child : node->children)
res += sum(child.second);
return res;
}
Node *root;
public:
/** Initialize your data structure here. */
MapSum() {
root = new Node();
}
void insert(string key, int val) {
Node *cur = root;
for (char c:key) {
if (cur->children.find(c) == cur->children.end())
cur->children.insert(make_pair(c, new Node()));
cur = cur->children[c];
}
cur->value = val;
}
int sum(string prefix) {
Node *cur = root;
for (char c: prefix) {
if (cur->children.find(c) == cur->children.end())
return false;
cur = cur->children[c];
}
return sum(cur);
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/
#709.转换成小写字母
class Solution {
public:
string toLowerCase(string str) {
for (char &c:str) {
if (c >= 'A' && c <= 'Z') {
c += 'a' - 'A';
}
}
return str;
}
};
#724.寻找数组的中心索引
class Solution {
public:
int pivotIndex(vector<int> &nums) {
if (nums.size() == 0)
return -1;
if (nums.size() == 1)
return 0;
int leftSum = 0;
int rightSum = 0;
for (int i = 1; i < nums.size(); ++i)
rightSum += nums[i];
int i;
for (i = 0; i < nums.size(); ++i) {
if (leftSum == rightSum)
return i;
leftSum += nums[i];
rightSum -= nums[i + 1];
}
return -1;
}
};
#728.自除数
class Solution {
private:
bool isSelfDividing(int n) {
string m = to_string(n);
for (int i = 0; i < m.size(); ++i) {
int digit = m[i] - '0';
if (digit == 0 || n % digit != 0)
return false;
}
return true;
}
public:
vector<int> selfDividingNumbers(int left, int right) {
vector<int> res;
if (left > right)
return res;
for (int i = left; i <= right; ++i) {
if (isSelfDividing(i)) {
res.push_back(i);
}
}
return res;
}
};
#747.至少是其他数字两倍的最大数
class Solution {
public:
int dominantIndex(vector<int> &nums) {
if (nums.size() == 1)
return 0;
int max = nums[0];
int maxIndex = 0;
for (int i = 1; i < nums.size(); ++i)
if (max < nums[i]) {
max = nums[i];
maxIndex = i;
}
for (int j = 0; j < nums.size(); ++j)
if (nums[j] != max && nums[j] != 0 && max / nums[j] < 2)
return -1;
return maxIndex;
}
};