There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.java
The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.數組
If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.ide
You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.this
Example:spa
Input:code
[[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]]
Output: 2blog
Explanation: rem
Note:get
如今有一個二維數組來表示一面牆,其中二維數組中每個值表明某一行的一顆磚塊的長度。如今會畫一條垂直的線,問最少須要跨過多塊磚。it
本質上就是記錄一下通過的全部磚塊縫隙,而後遇到重複的磚塊縫隙就將該爲止的磚塊縫隙數量加一。最後穿過越多的磚塊縫隙表明所須要穿過的磚塊數量越少。
public int leastBricks(List<List<Integer>> wall) { Map<Integer, Integer> map = new HashMap<>(); int row = wall.size(); int maxEdge = 0; for (List<Integer> bricks : wall) { int sumOfBrick = 0; for (int i = 0; i < bricks.size() - 1; i++) { int brick = bricks.get(i); sumOfBrick += brick; int edge = map.getOrDefault(sumOfBrick, 0) + 1; map.put(sumOfBrick, edge); maxEdge = Math.max(edge, maxEdge); } } return row - maxEdge; }