剑指 Offer 29. 顺时针打印矩阵
题目
思路
通过可视化限制四个方向运动的边界线
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix.length == 0) return new int[0];
int l = 0, r = matrix[0].length - 1, t = 0, b = matrix.length - 1, x = 0;
int[] res = new int[(r + 1) * (b + 1)];
while(true) {
for(int i = l; i <= r; i++) res[x++] = matrix[t][i]; // left to right.
if(++t > b) break;
for(int i = t; i <= b; i++) res[x++] = matrix[i][r]; // top to bottom.
if(l > --r) break;
for(int i = r; i >= l; i--) res[x++] = matrix[b][i]; // right to left.
if(t > --b) break;
for(int i = b; i >= t; i--) res[x++] = matrix[i][l]; // bottom to top.
if(++l > r) break;
}
return res;
}
}
class Solution:
def spiralOrder(self, matrix:[[int]]) -> [int]:
if not matrix: return []
l, r, t, b, res = 0, len(matrix[0]) - 1, 0, len(matrix) - 1, []
while True:
for i in range(l, r + 1): res.append(matrix[t][i]) # left to right
t += 1
if t > b: break
for i in range(t, b + 1): res.append(matrix[i][r]) # top to bottom
r -= 1
if l > r: break
for i in range(r, l - 1, -1): res.append(matrix[b][i]) # right to left
b -= 1
if t > b: break
for i in range(b, t - 1, -1): res.append(matrix[i][l]) # bottom to top
l += 1
if l > r: break
return res
剑指 Offer 30. 包含min函数的栈
题目
思路
使用两个栈来完成任务,A栈正常存储数据,B仅用于存储无绝对顺序的最小值,始终保持B的顶点存储着A的最小值(保证可以有O(1)的时间复杂度);
代码
class MinStack {
Stack<Integer> A,B;//全局变量其他的方法均可以调用这两个栈
/** initialize your data structure here. */
public MinStack() {
A=new Stack<Integer>();
B=new Stack<Integer>();
}
public void push(int x) {
A.add(x);
if(B.empty()||B.peek()>=x) B.add(x);//注意对于与B顶端存储的值相同的x也需要押送进B栈中,因为要与pop的方法相互对应。如果pop出一个最小值的话,B中应该还存有另一个相等的最小值
}
public void pop() {
// 注意此时A.pop()方法在if条件中,但是也相当于运行了A.pop()函数。
if(A.pop().equals(B.peek()))
B.pop();
}
public int top() {
return A.peek();
}
public int min() {
return B.peek();
}
}
/**
* 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.min();
*/
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.A=[]
self.B=[]
def push(self, x: int) -> None:
self.A.append(x)
if not self.B or self.B[-1]>=x: self.B.append(x)
def pop(self) -> None:
if self.A.pop()==self.B[-1]:
self.B.pop()
def top(self) -> int:
return self.A[-1]
def min(self) -> int:
return self.B[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()