题目链接:顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
数据范围
矩阵中元素数量 [0,400]
样例
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
class Solution {
public:
vector printMatrix(vector > matrix) {
vector res;
if (matrix.empty()) return res;
int n = matrix.size(), m = matrix[0].size();
int x = 0, y = 0, d = 1;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
vector> st(n, vector(m + 1, false));
for (int i = 0; i < n * m; i ++ )
{
res.push_back(matrix[x][y]);
st[x][y] = true;
int a = dx[d] + x, b = dy[d] + y;
if (a < 0 || b < 0 || a >= n || b >= m || st[a][b])
{
d = (d + 1) % 4;
a = dx[d] + x, b = dy[d] + y;
}
x = a, y = b;
}
return res;
}
};
整体思路
简单深搜罢了
可以背记一下遍历模板
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
for (int i = 0; i < 4; i ++ )
{
int a = x + dx[i], b = dy[i] + y;
if (a < 0 && b < 0 && a < n && b < m && (其他边界条件))
{
//
}
}
题目链接:包含min函数的栈
设计一个支持push,pop,top等操作并且可以在O(1)时间内检索出最小元素的堆栈。
push(x)–将元素x插入栈中
pop()–移除栈顶元素
top()–得到栈顶元素
getMin()–得到栈中最小元素
数据范围
操作命令总数 [0,100]
样例
MinStack minStack = new MinStack();
minStack.push(-1);
minStack.push(3);
minStack.push(-4);
minStack.getMin(); --> Returns -4.
minStack.pop();
minStack.top(); --> Returns 3.
minStack.getMin(); --> Returns -1.
class MinStack {
public:
/** initialize your data structure here. */
stack valStk;
stack minStk;
MinStack() {
}
void push(int x) {
valStk.push(x);
if (minStk.empty() || minStk.top() >= x) minStk.push(x);
}
void pop() {
if (minStk.top() == valStk.top()) minStk.pop();
valStk.pop();
}
int top() {
return valStk.top();
}
int getMin() {
return minStk.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
整体思路
单独维护一个栈即可
有点类似单调栈