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
Solution: Simulation
Note: width of ‘0’ is 1.
Time complexity: O(m*n*log(x))
Space complexity: O(1)
C++
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 |
// Author: Huahua class Solution { public: vector<int> findColumnWidth(vector<vector<int>>& grid) { vector<int> ans; for (int j = 0; j < grid[0].size(); ++j) { int maxWidth = 1; for (int i = 0; i < grid.size(); ++i) { int x = grid[i][j]; int width = 0; if (x < 0) { x = -x; ++width; } while (x) { x /= 10; ++width; } maxWidth = max(maxWidth, width); } ans.push_back(maxWidth); } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment