Re: [閒聊] 每日leetcode

作者: dont   2025-01-20 21:42:45
2661. First Completely Painted Row or Column
## 思路
先建表 num -> {r, c}
再跑arr, 用兩個陣列rows,cols紀錄該行列遇過的數字個數
如果都遇過(==lenC or lenR) 就回傳當前index
## Code
```cpp
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int lenR = mat.size(), lenC = mat[0].size();
vector<pair<int, int>> table(lenR * lenC + 1); // num -> {R, C}
for (int r = 0; r < lenR; ++r) {
for (int c = 0; c < lenC; ++c) {
table[mat[r][c]] = {r, c};
}
}
vector<int> rows(lenR, 0);
vector<int> cols(lenC, 0);
int n = arr.size();
for (int i=0; i < n; ++i) {
auto& [r, c] = table[arr[i]];
if (++rows[r] == lenC || ++cols[c] == lenR) {
return i;
}
}
return n;
}
};
```

Links booklink

Contact Us: admin [ a t ] ucptt.com