Given a picture consisting of black and white pixels, and a positive integer N, find the number of black pixels located at some specific row R and column C that align with all the following rules:

  1. Row R and column C both contain exactly N black pixels.
  2. For all rows that have a black pixel at column C, they should be exactly the same as row R

The picture is represented by a 2D char array consisting of 'B' and 'W', which means black and white pixels respectively.

Example:

Input:
[['W', 'B', 'W', 'B', 'B', 'W'],
['W', 'B', 'W', 'B', 'B', 'W'],
['W', 'B', 'W', 'B', 'B', 'W'],
['W', 'W', 'B', 'W', 'B', 'W']] N = 3
Output: 6
Explanation: All the bold 'B' are the black pixels we need (all 'B's at column 1 and 3).
0 1 2 3 4 5 column index
0 [['W', 'B', 'W', 'B', 'B', 'W'],
1 ['W', 'B', 'W', 'B', 'B', 'W'],
2 ['W', 'B', 'W', 'B', 'B', 'W'],
3 ['W', 'W', 'B', 'W', 'B', 'W']]
row index Take 'B' at row R = 0 and column C = 1 as an example:
Rule 1, row R = 0 and column C = 1 both have exactly N = 3 black pixels.
Rule 2, the rows have black pixel at column C = 1 are row 0, row 1 and row 2. They are exactly the same as row R = 0.

Note:

    1. The range of width and height of the input 2D array is [1,200].

531. Lonely Pixel I 的拓展,这题多了一个整数N,行和列可以最多含有N个黑元素。

解法:思路和531题一样,还是用一个行和一个列先统计黑元素的个数,然后在遍历一遍图,是黑元素并且行和列都等于N的就加到结果,最后返回结果。这题又多出一个条件2:要保证这N行的黑元素的位置要完全一样,可以一个一个的来比较。好的做法是把行元素转换成字符串或tuple,用一个哈希表记录行元素,然后直接比较行。

0[['W', 'B', 'W', 'B', 'B', 'W'],
1 ['W', 'W', 'B', 'B', 'B', 'W'],
2 ['W', 'B', 'W', 'B', 'B', 'W'],
3 ['W', 'B', 'W', 'W', 'B', 'W']]

Java:

public int findBlackPixel(char[][] picture, int N) {
int m = picture.length;
if (m == 0) return 0;
int n = picture[0].length;
if (n == 0) return 0; Map<String, Integer> map = new HashMap<>();
int[] colCount = new int[n]; for (int i = 0; i < m; i++) {
String key = scanRow(picture, i, N, colCount);
if (key.length() != 0) {
map.put(key, map.getOrDefault(key, 0) + 1);
}
} int result = 0;
for (String key : map.keySet()) {
if (map.get(key) == N) {
for (int j = 0; j < n; j++) {
if (key.charAt(j) == 'B' && colCount[j] == N) {
result += N;
}
}
}
} return result;
} private String scanRow(char[][] picture, int row, int target, int[] colCount) {
int n = picture[0].length;
int rowCount = 0;
StringBuilder sb = new StringBuilder(); for (int j = 0; j < n; j++) {
if (picture[row][j] == 'B') {
rowCount++;
colCount[j]++;
}
sb.append(picture[row][j]);
} if (rowCount == target) return sb.toString();
return "";
}  

Java: using hashmap to store the string of rows. So that we don't need to check rule 2

public int findBlackPixel(char[][] picture, int N) {
if (picture == null || picture.length == 0 || picture[0].length == 0) return 0;
int m = picture.length, n = picture[0].length;
int[] cols = new int[n];
Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < m; i++) {
int count = 0;
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; j++) {
if (picture[i][j] == 'B') {
cols[j]++;
count++;
}
sb.append(picture[i][j]);
}
if (count == N) {
String curRow = sb.toString();
map.put(curRow, map.getOrDefault(curRow, 0) + 1);
}
} int res = 0;
for (String row : map.keySet()) {
if (map.get(row) != N) continue;
for (int i = 0; i < n; i++) {
if (row.charAt(i) == 'B' && cols[i] == N) {
res += N;
}
}
}
return res;
} 

Python:

class Solution(object):
def findBlackPixel(self, picture, N):
"""
:type picture: List[List[str]]
:type N: int
:rtype: int
"""
rows, cols = [0] * len(picture), [0] * len(picture[0])
lookup = collections.defaultdict(int)
for i in xrange(len(picture)):
for j in xrange(len(picture[0])):
if picture[i][j] == 'B':
rows[i] += 1
cols[j] += 1
lookup[tuple(picture[i])] += 1 result = 0
for i in xrange(len(picture)):
if rows[i] == N and lookup[tuple(picture[i])] == N:
for j in xrange(len(picture[0])):
result += picture[i][j] == 'B' and cols[j] == N
return result

Python:  

class Solution(object):
def findBlackPixel(self, picture, N):
"""
:type picture: List[List[str]]
:type N: int
:rtype: int
"""
lookup = collections.Counter(map(tuple, picture))
cols = [col.count('B') for col in zip(*picture)]
return sum(N * zip(row, cols).count(('B', N)) \
for row, cnt in lookup.iteritems() \
if cnt == N == row.count('B'))

Python:

class Solution(object):
def findBlackPixel(self, picture, N):
"""
:type picture: List[List[str]]
:type N: int
:rtype: int
"""
w, h = len(picture), len(picture[0])
rows, cols = [0] * w, [0] * h
for x in range(w):
for y in range(h):
if picture[x][y] == 'B':
rows[x] += 1
cols[y] += 1 sdict = collections.defaultdict(int)
for idx, row in enumerate(picture):
sdict[''.join(row)] += 1 ans = 0
for x in range(w):
row = ''.join(picture[x])
if sdict[row] != N:
continue
for y in range(h):
if picture[x][y] == 'B':
if rows[x] == N:
if cols[y] == N:
ans += 1
return ans  

C++:

class Solution {
public:
int findBlackPixel(vector<vector<char>>& picture, int N) {
vector<int> rows = vector<int>(picture.size());
vector<int> cols = vector<int>(picture[0].size()); unordered_map<string, int> lookup;
vector<string> srows;
for (int i = 0; i < picture.size(); ++i) {
string s;
for (int j = 0; j < picture[0].size(); ++j) {
if (picture[i][j] == 'B') {
++rows[i];
++cols[j];
}
s.push_back(picture[i][j]);
}
++lookup[s];
srows.emplace_back(move(s));
} int result = 0;
for (int i = 0; i < picture.size(); ++i) {
if (rows[i] == N && lookup[srows[i]] == N) {
for (int j = 0; j < picture[0].size(); ++j) {
result += picture[i][j] == 'B' && cols[j] == N;
}
}
}
return result;
}
};

  

类似题目:

[LeetCode] 531. Lonely Pixel I 孤独的像素 I

All LeetCode Questions List 题目汇总

[LeetCode] 533. Lonely Pixel II 孤独的像素 II的更多相关文章

  1. [LeetCode] 531. Lonely Pixel I 孤独的像素 I

    Given a picture consisting of black and white pixels, find the number of black lonely pixels. The pi ...

  2. [LeetCode] Lonely Pixel I 孤独的像素之一

    Given a picture consisting of black and white pixels, find the number of black lonely pixels. The pi ...

  3. LeetCode 533. Lonely Pixel II (孤独的像素之二) $

    Given a picture consisting of black and white pixels, and a positive integer N, find the number of b ...

  4. [LeetCode] Lonely Pixel II 孤独的像素之二

    Given a picture consisting of black and white pixels, and a positive integer N, find the number of b ...

  5. LeetCode 531. Lonely Pixel I

    原题链接在这里:https://leetcode.com/problems/lonely-pixel-i/ 题目: Given a picture consisting of black and wh ...

  6. 533. Lonely Pixel II

    Given a picture consisting of black and white pixels, and a positive integer N, find the number of b ...

  7. LeetCode 531. Longly Pixel I (孤独的像素之一) $

    Given a picture consisting of black and white pixels, find the number of black lonely pixels. The pi ...

  8. Leetcode 137. 只出现一次的数字 II - 题解

    Leetcode 137. 只出现一次的数字 II - 题解 137. Single Number II 在线提交: https://leetcode.com/problems/single-numb ...

  9. [Leetcode 90]求含有重复数的子集 Subset II

    [题目] Given a collection of integers that might contain duplicates, nums, return all possible subsets ...

随机推荐

  1. 《逆袭团队》第九次团队作业【Beta】Scrum meeting 2

    项目 内容 软件工程 任课教师博客主页链接 作业链接地址 团队作业9:Beta冲刺与团队项目验收 团队名称 逆袭团队 具体目标 (1)掌握软件黑盒测试技术:(2)学会编制软件项目总结PPT.项目验收报 ...

  2. C#编写简单的聊天程序(转)

    这是一篇基于Socket进行网络编程的入门文章,我对于网络编程的学习并不够深入,这篇文章是对于自己知识的一个巩固,同时希望能为初学的朋友提供一点参考.文章大体分为四个部分:程序的分析与设计.C#网络编 ...

  3. Python2.7 报错:UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-4: ordinal not in range(128)

    一. 错误原因(网上找的是这样说的,具体的我也不是很了解2.7版本的编码问题): 1.python默认使用ASCII处理字符流. 2.Unicode编码与ASCII编码的不兼容,Python脚本文件是 ...

  4. svn服务的安装与设置 .

    1.  下载svn软件并安装,本人使用的是如下软件:                 TortoiseSVN-1.6.5.16974-win32-svn-1.6.5               Vis ...

  5. learning java 转换流

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public ...

  6. a list of frequently asked questions about Circus

    转自:https://circus.readthedocs.io/en/latest/faq/,可以帮助我们了解circus 的使用,以及问题解决 How does Circus stack comp ...

  7. C++之Lambda研究

    目录 目录 1 1. 前言 1 2. 示例1 1 3. 示例2 2 4. 示例3 3 5. 示例4 3 6. 示例5 6 7. 匿名类规则 6 8. 参考资料 7 1. 前言 本文代码测试环境为“GC ...

  8. something about 乘法逆元

    before 在求解除法取模问题(a / b) % m时,我们可以转化为(a % (b * m)) / b, 但是如果b很大,则会出现爆精度问题,所以我们避免使用除法直接计算. (逆元就像是倒数一样的 ...

  9. 使用css3变量创建炫酷悬停效果

    原文地址:www.zcfy.cc/article/stunning-hover-effects-with-css-variables 效果: 主要使用css中的var做动画效果,代码如下: <! ...

  10. nRF51822 的两路 PWM 极性

    忙了一阵这个PWM,玩着玩着终于发现了些规律.Nordic 也挺会坑爹的. nRF51822 是没有硬件 PWM 的,只能靠一系列难以理解的 PPI /GPIOTE/TIMER来实现,其实我想说,我醉 ...