554:砖墙

This commit is contained in:
huangge1199@hotmail.com 2021-05-02 22:59:57 +08:00
parent 2ef5a4c25b
commit 1244128c00
2 changed files with 111 additions and 0 deletions

View File

@ -0,0 +1,77 @@
//你的面前有一堵矩形的 n 行砖块组成的砖墙这些砖块高度相同也就是一个单位高但是宽度不同每一行砖块的宽度之和应该相等
//
// 你现在要画一条 自顶向下 穿过 最少 砖块的垂线如果你画的线只是从砖块的边缘经过就不算穿过这块砖你不能沿着墙的两个垂直边缘之一画线这样显然是没
//有穿过一块砖的
//
// 给你一个二维数组 wall 该数组包含这堵墙的相关信息其中wall[i] 是一个代表从左至右每块砖的宽度的数组你需要找出怎样画才能使这条线 穿过的
//砖块数量最少 并且返回 穿过的砖块数量
//
//
//
// 示例 1
//
//
//输入wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
//输出2
//
//
// 示例 2
//
//
//输入wall = [[1],[1],[1]]
//输出3
//
//
//
// 提示
//
//
// n == wall.length
// 1 <= n <= 104
// 1 <= wall[i].length <= 104
// 1 <= sum(wall[i].length) <= 2 * 104
// 对于每一行 i sum(wall[i]) 应当是相同的
// 1 <= wall[i][j] <= 231 - 1
//
// Related Topics 哈希表
// 👍 204 👎 0
package leetcode.editor.cn;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//554:砖墙
public class BrickWall {
public static void main(String[] args) {
//测试代码
Solution solution = new BrickWall().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int leastBricks(List<List<Integer>> wall) {
Map<Integer, Integer> map = new HashMap<>();
int lineWidth = 0;
for (List<Integer> line : wall) {
int width = 0;
for (int num : line) {
width += num;
map.put(width, map.getOrDefault(width, 0) + 1);
}
lineWidth = width;
}
int max = 0;
for (int key : map.keySet()) {
if (key != 0 && key != lineWidth) {
max = Math.max(max, map.get(key));
}
}
return wall.size() - max;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,34 @@
<p>你的面前有一堵矩形的、由 <code>n</code> 行砖块组成的砖墙。这些砖块高度相同(也就是一个单位高)但是宽度不同。每一行砖块的宽度之和应该相等。</p>
<p>你现在要画一条 <strong>自顶向下 </strong>的、穿过 <strong>最少 </strong>砖块的垂线。如果你画的线只是从砖块的边缘经过,就不算穿过这块砖。<strong>你不能沿着墙的两个垂直边缘之一画线,这样显然是没有穿过一块砖的。</strong></p>
<p>给你一个二维数组 <code>wall</code> ,该数组包含这堵墙的相关信息。其中,<code>wall[i]</code> 是一个代表从左至右每块砖的宽度的数组。你需要找出怎样画才能使这条线 <strong>穿过的砖块数量最少</strong> ,并且返回 <strong>穿过的砖块数量</strong></p>
<p> </p>
<p><strong>示例 1</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/24/cutwall-grid.jpg" style="width: 493px; height: 577px;" />
<pre>
<strong>输入:</strong>wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
<strong>输出:</strong>2
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>wall = [[1],[1],[1]]
<strong>输出:</strong>3
</pre>
 
<p><strong>提示:</strong></p>
<ul>
<li><code>n == wall.length</code></li>
<li><code>1 <= n <= 10<sup>4</sup></code></li>
<li><code>1 <= wall[i].length <= 10<sup>4</sup></code></li>
<li><code>1 <= sum(wall[i].length) <= 2 * 10<sup>4</sup></code></li>
<li>对于每一行 <code>i</code> <code>sum(wall[i])</code> 应当是相同的</li>
<li><code>1 <= wall[i][j] <= 2<sup>31</sup> - 1</code></li>
</ul>
<div><div>Related Topics</div><div><li>哈希表</li></div></div>\n<div><li>👍 204</li><li>👎 0</li></div>