剑指 Offer 29. 顺时针打印矩阵
菜鸡思路:
既然是模拟的话,那么我们可以考虑像搜索一样,创建一个bool
的标记数组,标记每个位置有没有被走过,有的话就按顺序依次转换方向。如果都输出了,就结束。
菜鸡代码:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {
};
}
int rows = matrix.size(), columns = matrix[0].size();
vector<vector<bool>> visited(rows, vector<bool>(columns));
int directions[4][2] = {
{
0, 1}, {
1, 0}, {
0, -1}, {
-1, 0}};
int size = rows * columns, dir = 0, row = 0, column = 0;
vector<int> result(size);
for (int i = 0; i < size; ++i) {
result[i] = matrix[row][column];
visited[row][column] = true;
int nextRow = row + directions[dir][0], nextColumn = column + directions[dir][1];
if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
dir = (dir + 1) % 4;
}
row += directions[dir][0];
column += directions[dir][1];
}
return result;
}
};
剑指 Offer 31. 栈的压入、弹出序列
菜鸡思路:
既然是模拟,我们又可以想到,模拟给出的数组对我们自己的栈进行压入和弹出操作。如果最后栈空且所有数字全部操作过,即算作成功,否则都不成功。
菜鸡代码:
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> myStack;
int i, j;
for (i = 0, j = 0; i < pushed.size() && j < popped.size(); ++i) {
myStack.push(pushed[i]);
while (j < popped.size()) {
if (!myStack.empty() && popped[j] == myStack.top()) {
myStack.pop();
j++;
} else {
break;
}
}
}
if (j != popped.size() || (j == popped.size() && i != pushed.size())) {
return false;
}
return true;
}
};