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 is 3 since -10 is of length 3.
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.
你給予一個從 0 開始的 m x n 整數陣列 grid。每列的寬度是該列中整數的最大長度。 比如,如果 grid = [[-10], [3], [12]],則唯一一列的寬度為 3,因為 -10 的長度為 3。 回傳一個大小為 n 的整數陣列 ans,其中 ans[i] 表示第 i 列的寬度。 對於具有 len 為數字的整數 x,如果 x 為非負數,則其長度等於 len; 否則,其長度等於 len + 1。
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.
Solution:
這題可以把陣列排程圖像的方式來斯考:
Input: grid =
row ->
[
[1],
col | [22],
V [333]
]
接著我們就遍歷直欄(col),
並且取出每個直欄對應的橫列(row),
Input: grid =
0 1 2
row ->
row\col [
0 [-15, 1, 3],
1 col | [15, 7, 12],
2 V [5, 6, -2]
]
也就是說 col 固定,row 從上到下掃描找出最大的數值轉字串的長度,
最後放到 ans 陣列中即可。
Code 1: BigO(m x n)
function findColumnWidth(grid: number[][]): number[] {
const rows: number = grid.length;
const cols: number = grid[0].length;
const ans: number[] = [];
for (let col = 0; col < cols; col++) {
let maxWidth: number = 0;
for (let row = 0; row < rows; row++) {
let value: number = grid[row][col];
let width: number = value.toString().length;
maxWidth = Math.max(maxWidth, width);
}
ans.push(maxWidth);
}
return ans;
};
FlowChart:
Example 1
Input: grid = [[1],[22],[333]] col 0 row 0 value 1 maxWidth 0 width 1 maxWidth 1 row 1 value 22 maxWidth 1 width 2 maxWidth 2 row 2 value 333 maxWidth 2 width 3 maxWidth 3 return ans; // [3]
Example 2
Input: grid = [[-15,1,3],[15,7,12],[5,6,-2]] col 0 row 0 value -15 maxWidth 0 width 3 maxWidth 3 row 1 value 15 maxWidth 3 width 2 maxWidth 3 row 2 value 5 maxWidth 3 width 1 maxWidth 3 col 1 row 0 value 1 maxWidth 0 width 1 maxWidth 1 row 1 value 7 maxWidth 1 width 1 maxWidth 1 row 2 value 6 maxWidth 1 width 1 maxWidth 1 col 2 row 0 value 3 maxWidth 0 width 1 maxWidth 1 row 1 value 12 maxWidth 1 width 2 maxWidth 2 row 2 value -2 maxWidth 2 width 2 maxWidth 2 return ans; // [3,1,2]