查询网格图中每一列的宽度
难度:
标签:
题目描述
You are given a 0-indexed m x n
integer matrix grid
. The width of a column is the maximum length of its integers.
- For example, if
grid = [[-10], [3], [12]]
, the width of the only column is3
since-10
is of length3
.
Return an integer array ans
of size n
where ans[i]
is the width of the ith
column.
The length of an integer x
with len
digits is equal to len
if x
is non-negative, and len + 1
otherwise.
Example 1:
Input: grid = [[1],[22],[333]] Output: [3] Explanation: In the 0th column, 333 is of length 3.
Example 2:
Input: grid = [[-15,1,3],[15,7,12],[5,6,-2]] Output: [3,1,2] Explanation: In the 0th column, only -15 is of length 3. In the 1st column, all integers are of length 1. In the 2nd column, both 12 and -2 are of length 2.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-109 <= grid[r][c] <= 109
代码结果
运行时间: 31 ms, 内存: 17.3 MB
/* 思路:
使用 Java Stream API 简化代码,
1. 对于每一列,计算每个元素的字符串长度。
2. 找到最大字符串长度,并存入结果数组。 */
import java.util.Arrays;
public class Solution {
public int[] findColumnWidth(int[][] grid) {
return Arrays.stream(grid[0]) // 从第一行开始
.mapToInt((v, j) -> Arrays.stream(grid) // 遍历每一列
.mapToInt(row -> String.valueOf(row[j]).length()) // 获取每个元素的字符串长度
.max().orElse(0)) // 找到该列的最大长度
.toArray(); // 转换为数组返回
}
}
解释
方法:
此题解通过遍历矩阵中的每一列,对于每列中的每个元素,将其转换为字符串并计算字符串的长度。通过在内部循环中维护一个变量tmp,记录当前列中最大的字符串长度。最后,将每列的最大长度存储到结果列表中并返回。
时间复杂度:
O(m*n)
空间复杂度:
O(n)
代码细节讲解
🦆
题解中提到`tmp = max(tmp, len(str(grid[i][j])))`计算字符串长度,为何不直接使用`str(abs(grid[i][j]))`来忽略负号,是否有考虑到负数长度的影响?
▷🦆
题解中没有提及如何处理空矩阵或极端情况下的输入,如`grid=[]`或`grid=[[]]`,解决方案中是否应该包含对这些情况的处理?
▷🦆
在题解的逻辑中,内循环遍历每列的所有元素来找最大宽度,是否有其他数据结构或方法可以减少遍历次数或提高效率?
▷🦆
题解提出的算法适用于任何大小的矩阵,但是否有必要对矩阵尺寸进行限制,以防止在极大矩阵上的性能问题?
▷