其他分享
首页 > 其他分享> > 554. Brick Wall

554. Brick Wall

作者:互联网

题目:

There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.

Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. 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.

Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.

 

Example 1:

Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
Output: 2

Example 2:

Input: wall = [[1],[1],[1]]
Output: 3

 

Constraints:

 

 

 

 

思路:

本题首先至少要想到用前面的数列和来记录砖的边缘,这里有个小细节,因为最边缘的两块砖不能计算,因此最后一块砖的最右侧并不需要记录。然后逆向思维,要找穿过最少的砖的列,我们就要找“最厚“的上下相连的砖的边缘。因为这里要找频数,因此用哈希表来作为存储容器。首先遍历每一行的砖,记录下当前行所存在的边缘,存入哈希表,key是边缘的index(即第几列),value是出现的次数。然后遍历哈希表,找出最大的value值,用墙的总高度减去这个最大值即可。

 

 

 

代码:

class Solution {

public:

    int leastBricks(vector<vector<int>>& wall) {

        unordered_map<int,int> record;

        for(auto &w:wall)

        {

            int cur=0;

            int n=w.size();

            for(int i=0;i<n-1;i++)

            {

                cur+=w[i];

                record[cur]++;

            }

        }

        int ans=0;

        for(auto &[key, value]:record)

        {

            ans=max(value,ans);

        }

        

        return wall.size()-ans;

    }

};


 

标签:Wall,554,value,bricks,int,ans,Brick,line,wall
来源: https://blog.csdn.net/weixin_49991368/article/details/116355108