[LeetCode] 2661. First Completely Painted Row or Column

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:
Example 1
image explanation for 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:
Example 2
image explanation for 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.length
n = mat[i].length
arr.length == m * n
1 <= m, n <= 105
1 <= m * n <= 105
1 <= arr[i], mat[r][c] <= m * n
All the integers of arr are unique.
All the integers of mat are unique.

找出叠涂元素。

给你一个下标从 0 开始的整数数组 arr 和一个 m x n 的整数 矩阵 mat 。arr 和 mat 都包含范围 [1,m * n] 内的 所有 整数。
从下标 0 开始遍历 arr 中的每个下标 i ,并将包含整数 arr[i] 的 mat 单元格涂色。
请你找出 arr 中在 mat 的某一行或某一列上都被涂色且下标最小的元素,并返回其下标 i 。

思路

我创建了三个hashmap,一个记录坐标值和坐标的关系<mat[i][j], num>,一个记录每一行 row 上已经被访问过的坐标的个数,一个记录每一列 col 上已经被访问过的坐标的个数。

复杂度

时间O(mn)
空间O(n)

代码

Java实现

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
26
27
28
29
30
31
class Solution {
public int firstCompleteIndex(int[] arr, int[][] mat) {
int m = mat.length;
int n = mat[0].length;
HashMap<Integer, int[]> map = new HashMap<>();
HashMap<Integer, Integer> rowMap = new HashMap<>();
HashMap<Integer, Integer> colMap = new HashMap<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int num = mat[i][j];
map.put(num, new int[] { i, j });
}
}

for (int i = 0; i < arr.length; i++) {
int num = arr[i];
int[] pos = map.get(num);
int x = pos[0];
int y = pos[1];
if (mat[x][y] == num) {
mat[x][y] = 0;
rowMap.put(x, rowMap.getOrDefault(x, 0) + 1);
colMap.put(y, colMap.getOrDefault(y, 0) + 1);
if (rowMap.get(x) == n || colMap.get(y) == m) {
return i;
}
}
}
return arr.length;
}
}

[LeetCode] 2661. First Completely Painted Row or Column
https://shurui91.github.io/posts/3543248498.html
Author
Aaron Liu
Posted on
November 30, 2023
Licensed under