题目链接题目描述
你的面前有一堵矩形的、由 Leetcode 554 砖墙_权值

你现在要画一条自顶向下的、穿过最少砖块的垂线。如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。你不能沿着墙的两个垂直边缘之一画线,这样显然是没有穿过一块砖的。

给你一个二维数组 Leetcode 554 砖墙_思维_02 ,该数组包含这堵墙的相关信息。其中,Leetcode 554 砖墙_i++_03

示例1

输入:wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]  
输出:2

提示:
Leetcode 554 砖墙_思维_04
Leetcode 554 砖墙_权值_05
Leetcode 554 砖墙_思维_06
Leetcode 554 砖墙_Leetcode_07
对于每一行 Leetcode 554 砖墙_i++_08Leetcode 554 砖墙_数组_09 是相同的
Leetcode 554 砖墙_思维_10

建立一个 Leetcode 554 砖墙_Leetcode_11,键值代表缝隙端点,寻找缝隙权值的最大值,末尾的最后一个缝隙不计算,然后遍历一下砖的总长度寻找最大值,最后的只需要总长度 - 权值最大值就是答案

class Solution {
public:
    int leastBricks(vector<vector<int>>& wall) {
        unordered_map<int,int> hash;
        int n = wall.size();
        for(int i = 0; i < n; i++)
        {
            int m = wall[i].size()-1, t = 0;
            for(int j = 0; j < m; j++)
            {
                t += wall[i][j];
                hash[t]++;
            }
        }
        int res = 0;
        for(unordered_map<int,int>::iterator it = hash.begin(); it != hash.end(); it++)
            res = max(res,it->second);
        return n - res;
    }
};