You are given a 0-indexed integer array arr, and an m x n integer matrix mat. arr and mat both contain all the integers in the range [1, m * n].
Go through each index i in arr starting from index 0 and paint the cell in mat containing the integer arr[i].
Return the smallest index i at which either a row or a column will be completely painted in mat.
Example 1:

Input: arr = [1,3,4,2], mat = [[1,4],[2,3]] Output: 2 Explanation: The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2].
Example 2:

Input: arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]] Output: 3 Explanation: The second column becomes fully painted at arr[3].
Constraints:
m == mat.lengthn = mat[i].lengtharr.length == m * n1 <= m, n <= 1051 <= m * n <= 1051 <= arr[i], mat[r][c] <= m * n- All the integers of
arrare unique. - All the integers of
matare unique.
Solution: Map + Counter
Use a map to store the position of each integer.
Use row counters and column counters to track how many elements have been painted.
Time complexity: O(m*n + m + n)
Space complexity: O(m*n + m + n)
C++
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Author: Huahua class Solution { public: int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) { const int m = mat.size(); const int n = mat[0].size(); vector<int> rows(m); vector<int> cols(n); vector<pair<int, int>> pos(m * n + 1); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) pos[mat[i][j]] = {i, j}; for (int i = 0; i < arr.size(); ++i) { auto [r, c] = pos[arr[i]]; if (++rows[r] == n) return i; if (++cols[c] == m) return i; } return -1; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.


Be First to Comment