HashMap-Very Stupid and straightforward HashMap solution -- Java


  • 0
    H

    I see a hashmap tag in this question, so I try to solve it using hashmap. we can also use two 2-d array to achieve this.

    Idea:Just use hashmap to count each line. The line with value 1 is the line that not overlap.

    public class Solution {
        public int islandPerimeter(int[][] grid) {
            Map<String, Integer> map = new HashMap<>();
    
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == 1) {
                        map.put(i+"r"+j, map.getOrDefault(i+"r"+j,0)+1);
                        map.put(i+"r"+(j+1), map.getOrDefault(i+"r"+(j+1),0)+1);
                        map.put(j+"c"+i, map.getOrDefault(j+"c"+i,0)+1);
                        map.put(j+"c"+(i+1), map.getOrDefault(j+"c"+(i+1),0)+1);
                    }
                }
            }
            int count = 0;
            for (String key: map.keySet()) {
                if (map.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.