Verbose Java solution without HashMap. 19ms beat 95%.


  • 0
    J
    public class Solution {
        public int findBlackPixel(char[][] picture, int N) {
            if (picture.length == 0 || picture[0].length == 0) return 0;
            int m = picture.length;
            int n = picture[0].length;
            int[] I = new int[m];
            int[] J = new int[n];
            for (int i = 0; i < m; i++) {
                int count = 0;
                for (int j = 0; j < n; j++) {
                    if (picture[i][j] == 'B') {
                        count++;
                    }
                }
                I[i] = count;
            }
            for (int j = 0; j < n; j++) {
                int count = 0;
                for (int i = 0; i < m; i++) {
                    if (picture[i][j] == 'B') {
                        count++;
                    }
                }
                J[j] = count;
            }
            int ret = 0;
            for (int j = 0; j < n; j++) {
                if (J[j] != N) {
                    continue;
                }
                int count = 0;
                boolean flag = true;
                String prev = null;
                for (int i = 0; i < m; i++) {
                    if (picture[i][j] == 'B' && I[i] == N) {
                        String cur = new String(picture[i]);
                        if (prev == null) {
                            prev = cur;
                        } else if (!prev.equals(cur)) {
                            flag = false;
                            break;
                        }
                        count++;
                    } else if (picture[i][j] == 'B') {
                        flag = false;
                        break; 
                    }
                }
                if (flag) {
                    ret += count;
                }
            }
            return ret;
        }
    }
    

Log in to reply
 

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