Java with HashMap


  • 0

    Count the cracks each line, and keep in a HashMap.
    Go through the most count cracks.

    public int leastBricks(List<List<Integer>> wall) {
            if(wall == null || wall.size() == 0) return 0;
            Map<Integer, Integer> map = new HashMap<>();
            int tot = wall.size();
            int length = 0;   //count the length of the wall
            for(List<Integer> list : wall) {
                int prev = 0;
                int temp = 0;
                for(int cur : list) {
                    temp += cur;
                    prev += cur;
                    map.put(prev, map.getOrDefault(prev, 0) + 1);
                }
                length = temp;
            }
            
            map.remove(length); //remove last edge
            int max = 0;
            for(int key : map.keySet()) {
                max = Math.max(max, map.get(key));
            }
            return max == 0 ? tot : tot - max;
        }
    

Log in to reply
 

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