Personal evaluation: two-dimensional array, I just want to violence 😂 and the efficiency is slightly worse, and so on for a while to think again

🌟🌟 (see LeeCode simple 🌟, medium 🌟🌟, difficult 🌟)

In addition, algorithm questions usually examine and analyze time complexity and space complexity, which can be referred to the author’s previous article

“Data Structures & Algorithms” series: 3. Time & Space Complexity (2)

Print matrix clockwise (helical matrix)

Topic describes

Finger Offer 29. Print matrix clockwise

54. Spiral matrix

You are given a matrix matrix with m rows and n columns. Please return all elements in the matrix in clockwise spiral order.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]

Output:,2,3,6,9,8,7,4,5 [1]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]

Output:,2,3,4,8,12,11,10,9,5,6,7 [1]

Tip:

m == matrix.length n == matrix[i].length 1 <= m, n <= 10 -100 <= matrix[i][j] <= 100

Their thinking

Individual did not think what better way, on the violence of the solution 😂 to find the rule, the idea is as follows:

  • There are four methods: → ↓ ← ↑ The elements added in each direction meet certain restrictions
  • Over the past number depends on m, n the smaller of the number (such as [[1, 2, 3, 4, 5,…, m], [2,3,4,5,6,3,…, m]] actually need only one time, even if m a lot)

Go implementation code is as follows:

func spiralOrder(matrix [][]int) []int {
    if len(matrix)==0 {
        return []int{}
    }
    lenX := len(matrix[0])
    lenY := len(matrix)
    list := []int{}
    numLoop := 2*lenX
    if lenY<lenX {
        numLoop = 2*lenY
    }
    for n:=0; n<numLoop; n++ {
        fmt.Println(n)
        if n%4= =0 { / / -
            list = append(list, matrix[n/4][n/4:lenX-n/4]...). fmt.Println(list) }if n%4= =1 { / / left
            for i:=(n- 1) /4+1; i< lenY-(n- 1) /4; i++ {
                list = append(list, matrix[i][lenX-(n- 1) /4- 1])
            }
            fmt.Println(list)
        }
        if n%4= =2 { / / please
            for j:=lenX-(n2 -) /42 -; j>=(n2 -) /4; j-- {
                list = append(list, matrix[lenY-(n2 -) /4- 1][j])
            }
            fmt.Println(list)
        }
        if n%4= =3 { / / write
            for i:=lenY-(n- 3) /42 -; i>(n- 3) /4; i-- {
                list = append(list, matrix[i][(n- 3) /4])
            }
            fmt.Println(list)
        }
    }
    return list
}
Copy the code

The boundary conditions are a little tricky 😓

Complexity? 🙌 time O(mn) Space O(1) The space complexity is constant except for the output array.

conclusion

On the contrary, I spent more time reading the problem solving series 😂 and found no better way than violence

So, perhaps which day suddenly thought of turning round 👀


This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign