HashMap solution Java


  • 0
    A
       public int findLonelyPixel(char[][] picture) {
        if(picture.length==0){
            return 0;
        } 
        HashMap<Integer, Integer> row = new HashMap<Integer, Integer>();
        HashMap<Integer, Integer> column = new HashMap<Integer, Integer>();
        for(int i=0; i<picture.length; i++){
            for(int j=0; j<picture[i].length; j++){
                if(picture[i][j]=='B')// check if row hash map already has black pixel, then set -1 otherwise column
                    if(row.containsKey(i)){
                        row.put(i, -1);
                    }
                    else{
                        row.put(i, j);
                  // check if column hash map already has black pixel, then set -1 otherwise 1
                    if(column.containsKey(j)){
                        column.put(j, -1);
                    }
                    else{
                        column.put(j, 1);
                    }
                }
            }
        }
        int count = 0;// check if row hash map of key is not -1 and the column hash map has value other than -1, then only count
        for(int key : row.keySet()){
            if(row.get(key)!=-1 && column.get(row.get(key))!=-1){
                count++;
            }
        }
        return count;
    }

Log in to reply
 

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