554. Brick Wall

来源:互联网 发布:销售数据分析表格模板 编辑:程序博客网 时间:2024/05/16 06:24

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.

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.

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.

Example:

Input: [[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]]Output: 2Explanation: 

Note:

  1. The width sum of bricks in different rows are the same and won't exceed INT_MAX.
  2. The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed 20,000.

思路:1. 最开始想到建立图,2.按照某种规则排序,3. 按层DP,
但是都想不下去,但都是想建立某种对应规则,记录层与层之间的对应关系,就是记住层与层之间的关系,
但仔细想一下第几层其实无所谓,主要考虑整体就好,所以就用HashTable


二刷:通过观察可以发现:一定是切在砖块的边缘,最后选择切入的地方一定是占有边缘数最多的地方,那就可用个HashTable计数就好了
package l554;import java.util.HashMap;import java.util.List;import java.util.Map;public class Solution {    public int leastBricks(List<List<Integer>> wall) {        Map<Integer, Integer> map = new HashMap<Integer, Integer>();                for(List<Integer> l : wall) {        int cnt = 0;        for(int i=0; i<l.size()-1; i++) {        cnt += l.get(i);        if(!map.containsKey(cnt))map.put(cnt, 1);        elsemap.put(cnt, map.get(cnt)+1);        }        }                int max = 0;        for(int i : map.keySet())        max = Math.max(max, map.get(i));        return wall.size() - max;    }}


原创粉丝点击