|
| 1 | +# 916. 2661. First Completely Painted Row or Column |
| 2 | + |
| 3 | +You are given a 0-indexed integer array `arr`, and an `m x n` integer matrix `mat`. |
| 4 | +`arr` and `mat` both contain all the integers in the range `[1, m * n]`. |
| 5 | + |
| 6 | +Go through each index `i` in `arr` starting from index `0` and |
| 7 | +paint the cell in `mat` containing the integer `arr[i]`. |
| 8 | + |
| 9 | +Return the smallest index `i` at which either a row or a column will be completely painted in `mat`. |
| 10 | + |
| 11 | +## 基礎思路 |
| 12 | +這題很重要的是建立索引列表,即數字對應到的行列,這樣可以快速找到對應的行列,然後進行計數,當計數等於m或n時,即找到答案。 |
| 13 | +對應表比較有效率的是構建兩個陣列,一個是行對應表,一個是列對應表,這樣可以快速找到對應的行列。 |
| 14 | +當然字典也是一個不錯的選擇,但是字典的查找效率比較低。 |
| 15 | + |
| 16 | +## 解題步驟 |
| 17 | + |
| 18 | +### Step 1: 取得行列數 |
| 19 | + |
| 20 | +```typescript |
| 21 | +const n = mat.length; // 行數 |
| 22 | +const m = mat[0].length; // 列數 |
| 23 | +``` |
| 24 | + |
| 25 | +### Step 2: 建立行列對應表 |
| 26 | + |
| 27 | +```typescript |
| 28 | +// 用來建立數字對應到行列的索引表 |
| 29 | +const numberToRow: number[] = new Array(n * m); |
| 30 | +const numberToCol: number[] = new Array(n * m); |
| 31 | + |
| 32 | +// 遍歷矩陣,建立數字對應到行列的索引表 |
| 33 | +for (let row = 0; row < n; row++) { |
| 34 | + for (let col = 0; col < m; col++) { |
| 35 | + const value = mat[row][col]; |
| 36 | + numberToRow[value] = row; |
| 37 | + numberToCol[value] = col; |
| 38 | + } |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +### Step 3: 利用行列對應表進行計數,並找到答案 |
| 43 | + |
| 44 | +```typescript |
| 45 | +// 用建立行列計數表 |
| 46 | +const rowCounts: number[] = new Array(n).fill(0); |
| 47 | +const colCounts: number[] = new Array(m).fill(0); |
| 48 | + |
| 49 | +// 遍歷arr,進行計數 |
| 50 | +for (let i = 0; i < arr.length; i++) { |
| 51 | + const current = arr[i]; |
| 52 | + const row = numberToRow[current]; |
| 53 | + const col = numberToCol[current]; |
| 54 | + |
| 55 | + // 更新行列計數 |
| 56 | + rowCounts[row]++; |
| 57 | + colCounts[col]++; |
| 58 | + |
| 59 | + // 判斷是否找到答案,即行計數等於m或列計數等於n |
| 60 | + if (rowCounts[row] === m || colCounts[col] === n) { |
| 61 | + return i; |
| 62 | + } |
| 63 | +} |
| 64 | +``` |
| 65 | + |
| 66 | +## Step 4: 返回-1 |
| 67 | + |
| 68 | +```typescript |
| 69 | +// 如果沒有找到答案,返回-1 |
| 70 | +return -1; |
| 71 | +``` |
| 72 | +雖然本題不會出現找不到答案的情況,但是實際應用中,這個是個好習慣。 |
| 73 | + |
| 74 | +## 時間複雜度 |
| 75 | +- 建立索引表的時間複雜度為$O(n \times m)$ |
| 76 | +- 遍歷arr的時間複雜度為$O(n \times m)$ |
| 77 | +- 總的時間複雜度為$O(n \times m)$ |
| 78 | + |
| 79 | +> $O(n \times m)$ |
| 80 | +
|
| 81 | +## 空間複雜度 |
| 82 | + |
| 83 | +- 兩個索引表的空間複雜度為$O(n \times m)$ |
| 84 | +- 兩個計數表的空間複雜度為$O(n + m)$ |
| 85 | +- 總的空間複雜度為$O(n \times m)$ |
| 86 | + |
| 87 | +> $O(n \times m)$ |
0 commit comments