zoukankan      html  css  js  c++  java
  • 0554. Brick Wall (M)

    Brick Wall (M)

    题目

    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: 2
    

    Explanation:

    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.

    题意

    给定一个砌墙图,每一行有若干个砖块,每个砖块宽度不定,现在从上往下垂直切到底,要求切到的砖块数量最少(切到两砖之缝不算切到砖块)。

    思路

    要求经过的砖块最少,等同于要求经过的缝隙最多。只要统计在每一列的缝隙的个数并进行比较即可。


    代码实现

    Java

    class Solution {
        public int leastBricks(List<List<Integer>> wall) {
            int max = 0;
            Map<Integer, Integer> map = new HashMap<>();
            for (List<Integer> row : wall) {
                int sum = 0;
                for (int i = 0; i < row.size() - 1; i++) {
                    sum += row.get(i);
                    map.put(sum, map.getOrDefault(sum, 0) + 1);
                    max = Math.max(max, map.get(sum));
                }
            }
            return wall.size() - max;
        }
    }
    
  • 相关阅读:
    常用坐标系椭球参数整理
    ArcEngine编辑保存错误:Unable to create logfile system tables
    ArcEngine:The XY domain on the spatial reference is not set or invalid错误
    dockManager中DockPanel的刷新问题!
    ibatis实现Iterate的使用
    mongodb用子文档做为查询条件的两种方法
    Eclipse中的文件导航插件StartExplorer
    mongoVUE的增删改查操作使用说明
    什么是脏读,不可重复读,幻读
    转:Maven常用命令
  • 原文地址:https://www.cnblogs.com/mapoos/p/14689825.html
Copyright © 2011-2022 走看看