春节刷题day19:LeetCode
剑指 Offer 13. 机器人的运动范围
剑指 Offer 33. 二叉搜索树的后序遍历序列
剑指 Offer 59 - II. 队列的最大值
剑指 Offer 31. 栈的压入、弹出序列
1、剑指 Offer 13. 机器人的运动范围
class Solution {
public:
int ans;
bool vis[105][105];
int dir[4][2] = {
{
0, -1}, {
0, 1}, {
-1, 0}, {
1, 0}};
int slove(int x, int y){
int ret = 0;
while(x){
ret += x % 10; x /= 10;
}
while(y){
ret += y % 10; y /= 10;
}
return ret;
}
bool check(pair<int, int> now, int m, int n, int k){
if(now.first >= m || now.first < 0) return false;
if(now.second >= n || now.second < 0) return false;
if(slove(now.first, now.second) > k) return false;
if(vis[now.first][now.second]) return false;
return true;
}
int movingCount(int m, int n, int k) {
pair<int, int>now;
queue< pair<int, int> > que;
que.push(make_pair(0, 0));
vis[0][0] = true;
while(!que.empty()){
now = que.front(); que.pop();
int ret = 0;
ans++;
for(int i = 0; i < 4; i++){
pair<int, int> nxt;
nxt.first = now.first + dir[i][0];
nxt.second = now.second + dir[i][1];
if(check(nxt, m, n, k)){
vis[nxt.first][nxt.second] = true;
que.push(nxt);
}
}
}
return ans;
}
};
2、剑指 Offer 33. 二叉搜索树的后序遍历序列
class Solution {
public:
bool slove(vector<int>& postorder, int x, int y){
if(x >= y) return true;
int a = x;
while(postorder[a] < postorder[y]) a++;
int b = a;
while(postorder[a] > postorder[y]) a++;
return a == y && slove(postorder, x, b - 1) && slove(postorder, b, y - 1);
}
bool verifyPostorder(vector<int>& postorder) {
return slove(postorder, 0, postorder.size() - 1);
}
};
3、剑指 Offer 59 - II. 队列的最大值
class MaxQueue {
public:
queue<int> que1;
deque<int> que2;
MaxQueue() {
;
}
int max_value() {
if(que2.size() == 0) return -1;
return que2.front();
}
void push_back(int value) {
que1.push(value);
while(!que2.empty() && que2.back() < value){
que2.pop_back();
}
que2.push_back(value);
}
int pop_front() {
if(que1.size() == 0) return -1;
int ans = que1.front();
que1.pop();
if(ans == que2.front()) que2.pop_front();
return ans;
}
};
/**
* Your MaxQueue object will be instantiated and called as such:
* MaxQueue* obj = new MaxQueue();
* int param_1 = obj->max_value();
* obj->push_back(value);
* int param_3 = obj->pop_front();
*/
4、剑指 Offer 31. 栈的压入、弹出序列
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> st;
int n = popped.size();
int j = 0;
for (int i = 0; i < pushed.size(); ++i){
st.push(pushed[i]);
while(!st.empty() && j < n && st.top() == popped[j]){
st.pop();
++j;
}
}
return st.empty();
}
};
2021/2/27。