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;
        }
    }
    
  • 相关阅读:
    【思考题】任意长度有理数乘法运算
    【排序】表插入排序算法(C语言版)
    JAVA中的反射
    JAVA中关于日期的最常见的操作
    Hibernate:基于HQL实现数据查询
    Hibernate与Mybatis对比
    使用idea实现SSM框架整合
    基于maven搭建hibernate运行环境
    MYSQL中的存储过程
    MySQL 索引
  • 原文地址:https://www.cnblogs.com/mapoos/p/14689825.html
Copyright © 2011-2022 走看看