LeetCode554. 砖墙(Java HashMap 统计前缀和)
作者:互联网
554. 砖墙(Java HashMap 统计前缀和)
链接:https://leetcode-cn.com/problems/brick-wall/solution/554-zhuan-qiang-java-hashmap-tong-ji-qia-ol5r/
解题思路
用HashMap来统计 key 为 边界下标, value 为 key为边界的次数
统计出来后遍历,找到出现次数最多的边界
用n-这个数 就是 答案
class Solution {
public int leastBricks(List<List<Integer>> wall) {
int n = wall.size();
//key为边界下标,value为key作为边界下标的次数
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
//统计key作为边界的次数
for(int i = 0; i < n; i++) {
int edge = 0;
//遍历的时候注意:j < wall.get(i).size()-1 而不是wall.get(i).size()
for(int j = 0; j < wall.get(i).size()-1; j++) {
edge += wall.get(i).get(j);
if(map.containsKey(edge)) {
map.put(edge, map.get(edge)+1);
} else {
map.put(edge, 1);
}
}
}
//遍历
Iterator iter = map.entrySet().iterator();
int max = 0;
while(iter.hasNext()) {
Map.Entry<Integer, Integer> entry = (Map.Entry<Integer, Integer>) iter.next();
Integer value = entry.getValue();
max = Math.max(value, max);
}
return n-max;
}
}
标签:map,Java,HashMap,get,wall,int,edge,LeetCode554 来源: https://blog.csdn.net/weixin_46100881/article/details/116347408