Easy Java Solution(beats 90% solutions)


  • 1
    R
    public class Solution {
        public int findBlackPixel(char[][] picture, int N) {
            int m = picture.length, n = picture[0].length;
            int[] row = new int[m], col = new int[n];
            
            for(int i = 0; i < m; i++) {
                for(int j = 0; j < n; ++j) {
                    if(picture[i][j] == 'B') {
                        row[i]++;
                        col[j]++;
                    }
                }
            }
            
            int count = 0;
            for(int j = 0; j < n; j++) {
                if(col[j] == N) {
                List<Integer> list = new ArrayList<>();
                int num = 0;
                for(int i = 0; i < m; ++i) {
                    if(picture[i][j] == 'B' && row[i] == N) {
                        num++;
                    }
                    if(picture[i][j] == 'B') list.add(i);
                }
                
                if(num > 0) {
                    boolean flag = true;
                    for(int x = 1; x < list.size(); ++x) {
                        if(!Arrays.equals(picture[list.get(x)], picture[list.get(x - 1)])){
                            flag = false;
                            break;
                        }
                    }
                        if(flag) count += num;
                  }
                }
            }
            
            return count;
        }
    }
    
    

  • 0
    A

    @rsrs3 Thank you for sharing! I think this is a great solution, simple and fast! I have one suggestion for improvement. In the for loop of columns, we can avoid the list and use a int variable denoting the previous row instead. This can save a little space and time.

    //check the number of pixels in each column and if it has N pixels
    //check if each row of its pixels has N pixels and is identical to each other
    for (int j = 0; j < picture[0].length; j++) {
    	if (columns[j] == N) {
    		boolean valid = false;
    		int prevRow = -1;
    		for (int i = 0; i < picture.length; i++) {
    			if (picture[i][j] == 'B') {
    				if (prevRow == -1 && row[i] == N || 
    					row[i] == N && Arrays.equals(picture[prevRow], picture[i])) {
    					prevRow = i;
    					valid = true;
    				} else {
    					valid = false;
    					break;
    				}
    			}
    		}
    		if (valid) {
    			result += N;
    		}
    	}
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.