[LeetCode]531. Lonely Pixel I
题目描述
思路
保存每一行的B的个数,然后计算值为B的点的行列B个数均为一的数目
代码
class Solution {
public:
int findLonelyPixel(vector<vector<char>>& picture) {
unordered_map<int, int> row, col;
int result = 0;
for (int i = 0; i < picture.size(); ++i){
for (int j = 0; j < picture[0].size(); ++j) {
if (picture[i][j] == 'B'){
++row[i];
++col[j];
}
}
}
for (int i = 0; i < picture.size(); ++i){
for (int j = 0; j < picture[0].size(); ++j) {
if (row[i] == 1 && col[j] == 1 && picture[i][j] == 'B'){
++result;
}
}
}
return result;
}
};
思路 update
扫描,对于B的点,行计数+1,列计数如果为0,就记录行数,如果大于0,就取负。
结果对列计数为正的进行统计,计算其中行计数为1的点即可(来自某个不愿透露姓名的展的教学)
代码 update
class Solution {
public:
int findLonelyPixel(vector<vector<char>>& picture) {
vector<int> row(picture.size(), 0), col(picture[0].size(), 0);
int result = 0;
for (int i = 0; i < picture.size(); ++i){
for (int j = 0; j < picture[0].size(); ++j){
if (picture[i][j] == 'B'){
++row[i];
if (col[j] == 0){
col[j] = i + 1;
}
else{
col[j] = -1;
}
}
}
}
for (int i = 0; i < col.size(); ++i){
if (col[i] > 0){
if (row[col[i] - 1] == 1){
++result;
}
}
}
return result;
}
};