2020-10-19
面试题 03.04. 化栈为队
用栈实现队列
class MyQueue {
public:
stack<int> que;
stack<int> temp;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
que.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(!temp.empty()) {
int value = temp.top();
temp.pop();
return value;
}else {
while(!que.empty()) {
temp.push(que.top());
que.pop();
}
int value = temp.top();
temp.pop();
return value;
}
}
/** Get the front element. */
int peek() {
if(!temp.empty()) {
return temp.top();
}else {
while(!que.empty()) {
temp.push(que.top());
que.pop();
}
return temp.top();
}
}
/** Returns whether the queue is empty. */
bool empty() {
return que.empty()&&temp.empty();
}
};
class CQueue {
public:
stack<int> st1;
stack<int> st2;
CQueue() {
}
void appendTail(int value) {
st1.push(value);
}
int deleteHead() {
if(st2.empty()) {
while(!st1.empty()) {
st2.push(st1.top());
st1.pop();
}
}
if(st2.empty()) return -1;
else {
int m = st2.top();
st2.pop();
return m;
}
}
};
class Solution {
public:
string makeGood(string s) {
string stack;
for(int i = 0; i < s.size(); i++) {
stack+=s[i];
int n= stack.size();
if(n>=2&&stack[n-1]+32 == stack[n-2] || stack[n-1]-32 == stack[n-2]) {
stack.resize(n-2);
}
}
return stack;
}
};
面试题 03.02. 栈的最小值
最小栈
剑指 Offer 30. 包含min函数的栈
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s;
stack<int> Min;
MinStack() {
}
void push(int x) {
s.push(x);
if(Min.empty()) {
Min.push(x);
}else {
Min.push(min(x,Min.top()));
}
}
void pop() {
s.pop();
Min.pop();
}
int top() {
return s.top();
}
int getMin() {
return Min.top();
}
};
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
stack<int> tmp;
stack<int> tmp2;
vector<int> res(nums1.size());
for(int i = 0; i < nums2.size(); i++) {
tmp.push(nums2[i]);
}
for(int i = 0; i < nums1.size(); i++) {
int temp,max=-1;
while(!tmp.empty()) {
temp = tmp.top();
if(nums1[i]<temp) {
max = temp;
}else if(nums1[i] == temp){
res[i] = max;
break;
}
tmp2.push(temp);
tmp.pop();
}
while(!tmp2.empty()) {
tmp.push(tmp2.top());
tmp2.pop();
}
}
return res;
}
};
class MyStack {
public:
queue<int> queue1;
queue<int> queue2;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
queue2.push(x);
while(!queue1.empty()) {
queue2.push(queue1.front());
queue1.pop();
}
swap(queue1,queue2);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int m = queue1.front();
queue1.pop();
return m;
}
/** Get the top element. */
int top() {
int m = queue1.front();
return m;
}
/** Returns whether the stack is empty. */
bool empty() {
return queue1.empty();
}
};
class Solution {
public:
vector<string> buildArray(vector<int>& target, int n) {
vector<string> res;
int tmp = 1;
for(int i = 0; i < target.size();) {
if(target[i] == tmp) {
res.push_back("Push");
i++;
}else {
res.push_back("Push");
res.push_back("Pop");
}
tmp++;
}
return res;
}
};
class Solution {
public:
int minOperations(vector<string>& logs) {
stack<string> s;
for(int i = 0; i < logs.size(); i++) {
if(!s.empty()) {
if(logs[i] == "../") s.pop();
else if(logs[i] == "./") continue;
else s.push(logs[i]);
}else {
if(logs[i] == "../"|| logs[i] == "./") continue;
else s.push(logs[i]);
}
}
int length = 0;
while(!s.empty()){
length++;
s.pop();
}
return length;
}
};
class Solution {
public:
string removeDuplicates(string S) {
stack<char> s;
for(int i = 0; i < S.size(); i++) {
if(!s.empty()) {
if(s.top() == S[i]) {
s.pop();
}else {
s.push(S[i]);
}
}else s.push(S[i]);
}
string res = "";
while(!s.empty()) {
res += s.top();
s.pop();
}
reverse(res.begin(),res.end());
return res;
}
};
class RecentCounter {
public:
queue<int> q;
RecentCounter() {
}
int ping(int t) {
q.push(t);
while (q.front() < t - 3000) q.pop();
return q.size();
}
};
2020-10-20
树
N叉树的前序遍历
N叉树的后序遍历
剑指 Offer 54. 二叉搜索树的第k大节点
左叶子之和
二叉树的层序遍历
二叉树的层次遍历 II
剑指 Offer 32 - II. 从上到下打印二叉树 II
二叉树的堂兄弟节点
剑指 Offer 28. 对称的二叉树
/**
* 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) {
return Judg(root,root);
}
bool Judg(TreeNode* left, TreeNode* right) {
if(left == NULL && right == NULL) return true;
if(left == NULL || right == NULL) return false;
if(left->val == right->val) {
return Judg(left->left,right->right)&&Judg(left->right,right->left);
}
return false;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> res;
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> res1;
vector<int> res2;
GetLeaves(root1);
for(int i = 0; i < res.size(); i++) {
res1.push_back(res[i]);
}
res.clear();
GetLeaves(root2);
for(int i = 0; i < res.size(); i++) {
res2.push_back(res[i]);
}
return res1 == res2;
}
void GetLeaves(TreeNode * tree) {
if(!tree) return ;
if(!tree->left && !tree->right) {
res.push_back(tree->val);
return ;
}
GetLeaves(tree->left);
GetLeaves(tree->right);
}
};
2020-10-21
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(!root) return true;
return abs(isHeight(root->left)-isHeight(root->right))<=1 && isBalanced(root->left) && isBalanced(root->right);
}
int isHeight(TreeNode * root) {
if(!root) return 0;
else return max(isHeight(root->left),isHeight(root->right))+1;
}
};
/**
* 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) {
return Height(root);
}
int Height(TreeNode* root) {
if(!root) return 0;
else return max(Height(root->left),Height(root->right))+1;
}
};
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
int maxDepth(Node* root) {
if(root==nullptr) return 0;
queue<Node*> q;
q.push(root);
int nums=0;
while(!q.empty()){
int sz=q.size();
for(int i=0;i<sz;i++){
Node* cur=q.front();
q.pop();
for(Node* it:cur->children)
q.push(it);
}
nums++;
}
return nums;
}
};
/**
* 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) {
return Tree(nums,0,nums.size()-1);
}
TreeNode* Tree(vector<int> nums, int L, int R) {
if(L>R) return NULL;
int mid = (L+R)>>1;
auto node = new TreeNode(nums[mid]);
node->left = Tree(nums,L,mid-1);
node->right = Tree(nums,mid+1,R);
return node;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL)return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
return (left == 0 || right == 0) ? left + right + 1 : min(left, right) + 1;
}
};
/**
* 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* mirrorTree(TreeNode* root) {
if(!root || (!root -> left && !root -> right)) return root;
swapNode(root);
mirrorTree(root -> left);
mirrorTree(root -> right);
return root;
}
void swapNode(TreeNode *node)
{
if(!node || (!node -> left && !node -> right)) return;
TreeNode *temp = node -> left;
node -> left = node -> right;
node -> right = temp;
}
};
2020-10-22
/**
* 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:
void inOrder(TreeNode* root,vector<int> &res)
{
if(root==NULL) return ;
inOrder(root->left,res);
res.push_back(root->val);
inOrder(root->right,res);
}
TreeNode* increasingBST(TreeNode* root) {
vector<int> res;
inOrder(root,res);
TreeNode *ans = new TreeNode(0),*cur=ans;
for(int v:res)
{
cur->right = new TreeNode(v);
cur=cur->right;
}
return ans->right;
}
};
/**
* 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 == NULL && root->right == NULL) {
return sum == root->val;
}
return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val);
}
};
class Solution {
public:
void traverse(TreeNode *root, string &res) {
if(root == NULL) return;
res += to_string(root->val);
if(root->left == NULL && root->right == NULL) return ;
res+="(";
traverse(root->left,res);
res += ")";
if(root->right != NULL) {
res+="(";
traverse(root->right,res);
res += ")";
}
}
string tree2str(TreeNode* t) {
string res;
traverse(t,res);
return res;
}
};
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(t1 == NULL) return t2;
if(t2 == NULL) return t1;
auto merged = new TreeNode(t1->val+t2->val);
merged->left = mergeTrees(t1->left,t2->left);
merged->right = mergeTrees(t1->right,t2->right);
return merged;
}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return root;
if(!root->left && !root->right) return root;
TreeNode *tmp = root->right;
root->right = root->left;
root->left = tmp;
invertTree(root->left);
invertTree(root->right);
return root;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while(root) {
if (root->val > p->val && root->val > q->val) {
root = root->left;
} else if (root->val < p->val && root->val < q->val) {
root = root->right;
} else return root;
}
return NULL;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL)return NULL;
if(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 ? left : right;
}
};
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == NULL && q == NULL) return true;
else if(p == NULL || q == NULL) return false;
else if(p->val != q->val) return false;
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
};
class Solution {
public:
bool isUnivalTree(TreeNode* root) {
if(!root) return true;
int number = root->val;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
TreeNode* node = q.front();
if(node->val != number) return false;
q.pop();
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
return true;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> num_set;
void in_order(TreeNode* node) {
if (node==NULL){
return;
}
in_order(node->left);
num_set.push_back(node->val);
in_order(node->right);
}
bool findTarget(TreeNode* root, int k) {
in_order(root);
int left=0;
int right=num_set.size()-1;
while (left<right){
int sum=num_set[left]+num_set[right];
if (sum==k){
return true;
}
if (sum<k){
left++;
}else{
right--;
}
}
return false;
}
};
2020-10-23
class Solution {
public:
int ans;
int depth(TreeNode* root) {
if(!root) return 0;
int L = depth(root->left);
int R = depth(root->right);
ans = max(ans,L+R+1);
return max(L,R)+1;
}
int diameterOfBinaryTree(TreeNode* root) {
ans = 1;
depth(root);
return ans-1;
}
};
/**
* 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:
map<int,int> m;
void in_order(TreeNode* node) {
if (node==NULL){
return;
}
in_order(node->left);
m[node->val]++;
in_order(node->right);
}
vector<int> findMode(TreeNode* root) {
in_order(root);
vector<int> res;
int max = 0;
for(auto mm: m) {
if(mm.second>max) max = mm.second;
}
for(auto mm: m) {
if(mm.second==max) res.push_back(mm.first);
}
return res;
}
};
class Solution {
public:
set<int> s;
void In_Order(TreeNode* root) {
if(!root) return;
s.insert(root->val);
In_Order(root->left);
In_Order(root->right);
}
int findSecondMinimumValue(TreeNode* root) {
if(!root) return -1;
In_Order(root);
vector<int> res;
res.assign(s.begin(),s.end());
sort(res.begin(),res.end());
return res.size()==1? -1:res[1];
}
};
class Solution {
public:
TreeNode* traversal(vector<int>& nums, int left, int right) {
if(left>right) return NULL;
int mid = (left+right)>>1;
TreeNode* node = new TreeNode(nums[mid]);
node->left = traversal(nums,left,mid-1);
node->right = traversal(nums,mid+1,right);
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return traversal(nums,0,nums.size()-1);
}
};
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if (s == NULL) return false;
if (dfs(s, t)) return true;
return (isSubtree(s->left, t) || isSubtree(s->right, t));
}
bool dfs(TreeNode* s, TreeNode* t) {
if (s == NULL && t == NULL) return true;
if (s == NULL || t == NULL) return false;
if (s->val != t->val) return false;
return (dfs(s->left, t->left) && dfs(s->right, t->right));
}
};
class Solution {
public:
int findTilt(TreeNode* root) {
if (nullptr == root){
return 0;
}
return abs(dfs(root->left) - dfs(root->right)) + findTilt(root->left) + findTilt(root->right);
}
int dfs(TreeNode* root){
if (nullptr == root){
return 0;
}
return root->val + dfs(root->left) + dfs(root->right);
}
};
class Solution {
public:
TreeNode *ans = new TreeNode(0),*cur=ans;
void inOrder(TreeNode* node)
{
if(node==NULL) return ;
inOrder(node->left);
node->left=NULL; //将该节点的左孩子设为NULL
cur->right=node; //将该节点赋给上一个节点的右孩子
cur=node; //更新cur
inOrder(node->right);
}
TreeNode* convertBiNode(TreeNode* root) {
inOrder(root);
return ans->right;
}
};
2020-10-24
二叉树的层平均值
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
auto averages = vector<double>();
auto q = queue<TreeNode*>();
q.push(root);
while (!q.empty()) {
double sum = 0;
int size = q.size();
for (int i = 0; i < size; i++) {
auto node = q.front();
q.pop();
sum += node->val;
auto left = node->left, right = node->right;
if (left != nullptr) {
q.push(left);
}
if (right != nullptr) {
q.push(right);
}
}
averages.push_back(sum / size);
}
return averages;
}
};
class Solution {
public:
void dfs(TreeNode*root, int &pre, int &ans) {
if(!root) return ;
dfs(root->left,pre,ans);
if (pre == -1) {
pre = root->val;
} else {
ans = min(ans, root->val - pre);
pre = root->val;
}
dfs(root->right,pre,ans);
}
int getMinimumDifference(TreeNode* root) {
int ans = INT_MAX, pre = -1;
dfs(root, pre, ans);
return ans;
}
};
class Solution {
public:
void dfs(TreeNode*root, vector<string>& res,string tmp) {
if(!root) return ;
tmp += to_string(root->val);
if(root->left == NULL&&root->right == NULL) {res.push_back(tmp);tmp = "";}
else{
tmp+="->";
dfs(root->left,res,tmp);
dfs(root->right,res,tmp);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
string tmp;
dfs(root,res,tmp);
return res;
}
};
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(!root || root->val < low || root->val > high) return NULL;
root->left = trimBST(root->left,low,high);
root->right = trimBST(root->right,low,high);
return root;
}
};
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == NULL || val == root->val) return root;
return val < root->val ? searchBST(root->left, val) : searchBST(root->right, val);
}
};
class Solution {
public:
int sum = 0;
int rangeSumBST(TreeNode* root, int L, int R) {
if(!root) return sum;
if(root->val >= L && root->val <= R) sum+= root->val;
rangeSumBST(root->left,L,R);
rangeSumBST(root->right,L,R);
return sum;
}
};
class Solution {
public:
int total_sum = 0;
void dfs(TreeNode* node, int num){
if (node == nullptr){
return;
}
num = (num << 1) + node->val;
if (node->left == nullptr && node->right == nullptr){
total_sum += num;
return;
}
dfs(node->left, num);
dfs(node->right, num);
}
int sumRootToLeaf(TreeNode* root) {
total_sum = 0;
dfs(root, 0);
return total_sum;
}
};
2020-10-25
动态规划
class Solution {
public:
int massage(vector<int>& nums) {
int n = nums.size();
if(!n) return 0;
int dp0 = 0;
int dp1 = nums[0];
for(int i = 1; i < n; i++) {
int tdp0 = max(dp0,dp1);
int tdp1 = dp0+nums[i];
dp0 = tdp0;
dp1 = tdp1;
}
return max(dp0,dp1);
}
};
class Solution {
public:
int maxProfit(vector<int>& prices) {
int minprice = INT_MAX;
int maxprofit = 0;
for (auto price : prices){
maxprofit = max(maxprofit, price - minprice);
minprice = min(minprice, price);
}
return maxprofit;
}
};
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
vector<int> minCost(n);
minCost[0] = 0;
minCost[1] = min(cost[0],cost[1]);
for(int i = 2; i < n; i++) {
minCost[i] = min(minCost[i-1]+cost[i],minCost[i-2]+cost[i-1]);
}
return minCost[n-1];
}
};
class Solution {
public:
int waysToStep(int n) {
if(n == 1) return 1;
if(n == 2) return 2;
if(n == 3) return 4;
long dp[n + 1]; //dp[i]:存的是到 i 阶楼的所有方法总数
dp[1] = 1;
dp[2] = 2;
dp[3] = 4;
for(int i =4;i <= n;i ++){
dp[i] = (dp[i - 1] + dp[i - 2] + dp[i - 3])%1000000007;
}
return (int)dp[n];
}
};
class Solution {
public:
bool isSubsequence(string s, string t) {
int n = s.size();
int i = 0;
for(auto tt:t) {
if(tt == s[i]) {
i++;
}
}
if(i == n) return true;
return false;
}
};
class NumArray {
public:
int* sum;
NumArray(vector<int>& nums) {
sum = new int[nums.size()+1];
for(int i = 0; i < nums.size(); i++) {
sum[i+1] = sum[i]+nums[i];
}
}
int sumRange(int i, int j) {
return sum[j+1] - sum[i];
}
};
剑指 Offer 42. 连续子数组的最大和
面试题 16.17. 连续数列
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
for(int i = 1; i < n; i++) {
nums[i] = max(nums[i],nums[i]+nums[i-1]);
}
return *max_element(nums.begin(),nums.end());
}
};