Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124

Xin chào mọi người! Mình là Loser1 từ Learning AI with Loser. Hôm nay chúng ta sẽ tạm nghỉ ngơi sau 2 bài Hard liên tiếp với một bài Medium nhẹ nhàng hơn nhé! Let’s paint it! 🖌️
Chào anh em, các ae có thể xem Đề bài và Solution của mình trên LeetCode nhé:
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 * narr are unique.mat are unique.Cho một mảng arr và một ma trận mat. Mỗi phần tử trong arr sẽ "tô màu" một ô trong ma trận mat. Nhiệm vụ của chúng ta là tìm chỉ số đầu tiên trong arr mà tại đó, một hàng hoặc một cột trong ma trận được tô đầy đủ.
Khi mới nhìn vào bài này, mình cảm giác như đang chơi một game tô màu vậy! 🎮
Tưởng tượng bạn có:
Ma trận: Mảng arr để tô:
1 4 [1, 3, 4, 2]
2 3Quá trình tô màu sẽ diễn ra như sau:
Step 1: Tô số 1 Step 2: Tô số 3 Step 3: Tô số 4
🟦 ⬜️ 🟦 ⬜️ 🟦 🟦
⬜️ ⬜️ ⬜️ 🟦 ⬜️ 🟦
(Hàng 1 đã tô xong!)Điều quan trọng ta nhận ra là:
class Solution {
public:
int firstCompleteIndex(vector<int>& arr, vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
// Bước 1: Tạo map lưu tọa độ
unordered_map<int, pair<int, int>> cordi;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
cordi[mat[i][j]] = {i, j};
}
}
// Bước 2: Khởi tạo counters cho rows và cols
unordered_map<int, int> row, col;
// Bước 3: Bắt đầu tô màu!
for (int i = 0; i < arr.size(); ++i) {
auto [x, y] = cordi[arr[i]];
// Cập nhật số ô đã tô
row[x]++;
col[y]++;
// Kiểm tra điều kiện thắng
if (row[x] == n || col[y] == m) {
return i;
}
}
return -1; // Trường hợp không tìm thấy
}
};Chúc mọi người code vui! Hẹn gặp lại trong các bài Leetcode tiếp theo! 🚀
P/S: Follow mình tại Learning AI with Loser để cập nhật các bài giải Leetcode hàng ngày nhé! 💻✨
CODE EDITOR
#leetcode #leetcodedaily #algorithms #programming #learningwithlosers