Guest User

Untitled

a guest
Jul 21st, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. //HashMap + Array solution: generate a signature for each row and put it in the hashmap; only check for signatures with freq N
  2. //Time: O(m * n), 14ms
  3. //Space: O(m * n)
  4. class Solution {
  5. public int findBlackPixel(char[][] picture, int N) {
  6. int m = picture.length;
  7. if(m == 0) return 0;
  8. int n = picture[0].length;
  9. if(n == 0) return 0;
  10.  
  11. Map<String, Integer> map = new HashMap<>();
  12. int[] colCount = new int[n];
  13.  
  14. for(int i = 0; i < m; i++) {
  15. String s = countRow(picture, N, i, colCount);
  16. if(s.length() != 0) {
  17. map.put(s, map.getOrDefault(s, 0) + 1);
  18. }
  19. }
  20.  
  21. int ans = 0;
  22. for(String s : map.keySet()) {
  23. if(map.get(s) == N) {//Check for rows that possibly contain the pixels we are looking for
  24. for(int i = 0; i < s.length(); i++) {
  25. if(s.charAt(i) == 'B' && colCount[i] == N) {
  26. ans += N;
  27. }
  28. }
  29. }
  30. }
  31. return ans;
  32. }
  33.  
  34. //Generate a signature for each row if there are N Bs in the row and put it in the map
  35. //Update the colCount
  36. private String countRow(char[][] picture, int N, int r, int[] colCount) {
  37. int count = 0;
  38. StringBuilder s = new StringBuilder();
  39. for(int i = 0; i < picture[0].length; i++) {
  40. if(picture[r][i] == 'B') {
  41. count++;
  42. colCount[i]++;
  43. }
  44. s.append(picture[r][i]);
  45. }
  46. if(count == N) {
  47. return s.toString();
  48. }
  49. return "";
  50. }
  51. }
Add Comment
Please, Sign In to add comment