[剑指Offer] Day 25: Simulation

Authored by Tony Feng

Created on May 6th, 2022

Last Modified on May 30th, 2022

Task 1 - Q29. 顺时针打印矩阵

Question

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

Solution 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        ans = []
        while matrix:
            '''
            1) Extract the top of the matrix
            2) Reverse the matrix in a counter-clockwise direction
            '''
            ans.append(matrix.pop(0))
            matrix = list(zip(*matrix))[::-1] # zip(*a) is equal to zip(a[0], a[1], a[2], ...)
        return ans

Solution 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix: return []

        l, r, t, b = 0, len(matrix[0])-1, 0, len(matrix)-1
        ans = []

        # Follows the clockwise oreder and shrink the range
        while True:
            for i in range(l, r+1): 
                ans.append(matrix[t][i]) # left to right
            t += 1
            if t > b: break

            for i in range(t, b+1): 
                ans.append(matrix[i][r]) # top to bottom
            r -= 1
            if l > r: break

            for i in range(r, l-1, -1): 
                ans.append(matrix[b][i]) # right to left
            b -= 1
            if t > b: break

            for i in range(b, t-1, -1): 
                ans.append(matrix[i][l]) # bottom to top
            l += 1
            if l > r: 
                break

        return ans

Explanation

  • Solution 1
    • Time Complexity: O(M * N)
    • Space Complexity: O(M * N)
  • Solution 2
    • Time Complexity: O(M * N)
    • Space Complexity: O(1)

Task 2 - Q31. 栈的压入、弹出序列

Question

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。

例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。

push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Solution

1
2
3
4
5
6
7
8
9
class Solution: 
    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
        stack, i = [], 0    # A pointer pointing to the popped list
        for num in pushed:
            stack.append(num) 
            while stack and stack[-1] == popped[i]: 
                stack.pop()
                i += 1
        return True if not stack else False

Explanation

  • Time Complexity: O(N)
  • Space Complexity: O(N)

MIT License
Last updated on May 30, 2022 11:35 EDT
Built with Hugo
Theme Stack designed by Jimmy