剑指 Offer 29. 顺时针打印矩阵
四个循环遍历即可
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int>ans;
if(matrix.size()==0||matrix[0].size()==0) return ans;
int i=0,j=0,cal=matrix.size(),row=matrix[0].size(),x=0,y=0,p=cal,q=row;
while(ans.size()<p*q){
while(j<row){
ans.push_back(matrix[i][j]);
j++;
}
if(ans.size()==p*q) break;
j--;i++;x++;
while(i<cal){
ans.push_back(matrix[i][j]);
i++;
}
if(ans.size()==p*q) break;
i--;j--;row--;
while(j>=y){
ans.push_back(matrix[i][j]);
j--;
}
if(ans.size()==p*q) break;
j++;i--;cal--;
while(i>=x){
ans.push_back(matrix[i][j]);
i--;
}
if(ans.size()==p*q) break;
i++;j++;y++;
}
return ans;
}
};
剑指 Offer 31. 栈的压入、弹出序列
判断出栈和入栈位置即可,最后判断栈是否为空
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int>s;
int i=0;
int j=0;
int flag=1;
while(flag){
if(s.size()==0){
if(i==pushed.size()) break;
s.push(pushed[i++]);
}
else{
if(s.top()==popped[j]){
s.pop();
j++;
}
else{
if(i==pushed.size()) break;
s.push(pushed[i++]);
}
}
}
if(s.size()==0) return true;
else return false;
}
};