Java Solution O(mn) using hash


  • 0
    C
     public int findLonelyPixel(char[][] picture) {
            Map<String, Integer> invalidPos = new HashMap<String, Integer>();
            List<int[]> potentialLonePixels = new ArrayList<int[]>();
            
            for(int i=0; i<picture.length; i++){
                for(int j=0; j<picture[0].length; j++){
                    if(picture[i][j] == 'B'){
                        String str1 = i + "-*";
                        String str2 = "*-" + j;
                        
                        int val1 = invalidPos.getOrDefault(str1, 0) + 1;
                        int val2 = invalidPos.getOrDefault(str2, 0) + 1;
                        
                        if(val1<2 && val2<2){
                            potentialLonePixels.add(new int[]{i,j});
                        }
                        
                        invalidPos.put(str1, val1);
                        invalidPos.put(str2, val2);
                    }
                }
            }
            
            int count = 0;
            for(int[] pos : potentialLonePixels){
                String str1 = pos[0] + "-*";
                String str2 = "*-" + pos[1];
                
                if(invalidPos.getOrDefault(str1, 0) < 2 && invalidPos.getOrDefault(str2, 0) < 2){
                    count++;
                }
            }
            
            return count;
        }
    

Log in to reply
 

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