This article is participating in the “Java Theme Month – Java Brush questions punch card”, see the activity link for details
Topic describes
This is the 867. Transpose matrix on LeetCode.
Tag: “Simulation”
Given a two-dimensional integer array matrix, return the transpose of matrix.
The transpose of a matrix is to reverse the main diagonal of the matrix and swap the row index and column index of the matrix.
Example 1:
Input: matrix = [[1, 2, 3], [4 and 6], [7,8,9]] output: [,4,7 [1], [2,5,8], [3,6,9]]Copy the code
Example 2:
Input: matrix = [[1, 2, 3], [4 and 6]] output: [[1, 4], [2, 5], [3]]Copy the code
Tip:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 1000
- 1 <= m * n <=
- –
<= matrix[i][j] <=
simulation
The diagonal flip, you just simulate it from the beginning.
class Solution {
public int[][] transpose(int[][] matrix) {
int n = matrix.length, m = matrix[0].length;
int[][] ans = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) { ans[i][j] = matrix[j][i]; }}returnans; }}Copy the code
- Time complexity: O(n∗m)O(n * m)O(n∗m)
- Space complexity: Use the same amount of space to store the answer. The complexity is O(n∗m)O(n * m)O(n∗m)
Matrix questions
The title is so simple that you wonder if the LeetCode team is still on vacation.
I’ve picked out a few moderately difficult matrix transformations on LeetCode, so if you’re not having fun with today’s “Problem of the Day”, you can try them:
566. Remodeling matrices (easy)
54. Spiral matrix (Medium)
59. Spiral Matrix II(Medium)
A note on complexity
Both time and space are used to describe the resource consumption required by the operation of the algorithm
O(n * m)O(n∗m) O(n * m)O(n∗m)
O(1)O(1)O(1) O(1
Just like when we solve problems recursively, the stack frames themselves consume memory. So when you do a complexity analysis, you should be careful to show the space cost of ignoring recursion
The last
This is the No.867 of our “Brush through LeetCode” series, which started on 2021/01/01. There are 1916 topics in LeetCode as of the start date, some of which have locks.
In this series of articles, in addition to explaining how to solve the problem, I will also present the most concise code possible. If a general solution is involved, the corresponding code template will also be used.
In order to facilitate the students to debug and submit the code on the computer, I set up the relevant warehouse: github.com/SharingSour… .
In the repository, you’ll see links to the series of articles, the corresponding code for the series of articles, the LeetCode source links, and other preferred solutions.