Easy O(N) Java Solution Using HashMap


  • 0
    public class Solution {
        public int leastBricks(List<List<Integer>> wall) {
            if (wall == null || wall.size() == 0) {
                return 0;
            }
            int max = 0;
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (List<Integer> list : wall) {
                int position = 0;
                for (int i = 0; i < list.size(); i++) {
                    position += list.get(i);
                    if (!map.containsKey(position)) {
                        map.put(position, 1);
                    } else {
                        map.put(position, map.get(position) + 1);
                    }
    
                    if (i != list.size() - 1) {
                        max = Math.max(max, map.get(position));
                    }
                }
            }
    
            return wall.size() - max;
        }
    }
    

Log in to reply
 

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