题目思路其实挺简单,找到每一行边界所处的位置,然后统计就可以。
但是这样很容易超内存,或者超时。
class Solution {
public int leastBricks(List<List<Integer>> wall) {
int row = wall.size();
int sum = 0;
List<Integer> tmp = wall.get(0);
for(int i=0;i<tmp.size();i++){
sum += tmp.get(i);
}
int[][] dp = new int[row][sum+1];
for(int i=0;i<row;i++){
List<Integer> tmp1 = wall.get(i);
int index = 0;
for(int j=0;j<tmp1.size();j++){
index += tmp1.get(j);
dp[i][index] = 1;
}
}
int max = 0;
for(int i = 1;i<sum;i++){
int sum1 = 0;
for(int j =0;j<row;j++){
sum1 += dp[j][i];
}
max = Math.max(max,sum1);
}
return row-max;
}
}```
因此,可以采用hashmap的方式
```java
class Solution {
public int leastBricks(List<List<Integer>> wall) {
int row = wall.size();
int sum = 0;
List<Integer> tmp = wall.get(0);
for(int i=0;i<tmp.size();i++){
sum += tmp.get(i);
}
HashMap<Integer,Integer> map = new HashMap<>();
for(int i=0;i<row;i++){
List<Integer> tmp1 = wall.get(i);
int id = 0;
for(int j = 0;j<tmp1.size();j++){
id += tmp1.get(j);
if(map.containsKey(id)){
map.put(id,map.get(id)+1);
}else{
map.put(id,1);
}
}
}
int max = 0;
for(int s: map.keySet()){
if(s!=sum){
max = Math.max(max,map.get(s));
}
}
return row-max;
}
}