虚拟单位解法 JAVA:
/** * @Author Niuxy * @Date 2020/11/16 11:29 下午 * @Description 虚拟砖块 */ public final int leastBricks(List<List<Integer>> wall) { int[] column = new int[wall.size()]; int sum = 0, res = Integer.MAX_VALUE; for (int i = 0; i < wall.get(0).size(); i++) sum += wall.get(0).get(i); for (int i = 0; i < sum; i++) { int currentColumnRe = 0; for (int j = 0; j < wall.size(); j++) { List<Integer> row = wall.get(j); if (row.get(column[j]) == 0) column[j]++; else currentColumnRe++; row.set(column[j], row.get(column[j]) - 1); } res = Math.min(res, currentColumnRe); } return res; }
前缀和解法 JAVA:
public final int leastBricks(List<List<Integer>> wall) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (List<Integer> row : wall) { int gap = 0; for (int i = 0; i < row.size() - 1; i++) { gap += row.get(i); if (map.containsKey(gap)) map.put(gap, map.get(gap) + 1); else map.put(gap, 1); } } Iterator<Integer> iterator = map.keySet().iterator(); int maxGap = 0; while (iterator.hasNext()) { int key = iterator.next(); maxGap = Math.max(maxGap, map.get(key)); } return wall.size() - maxGap; }
前缀和解法 JS:
/** * @param {number[][]} wall * @return {number} */ var leastBricks = function (wall) { let map = new Map(); for (let i = 0; i < wall.length; i++) { let gap = 0; for (let j = 0; j < wall[i].length - 1; j++) { gap += wall[i][j]; if (!map.get(gap)) map.set(gap, 1); else map.set(gap, map.get(gap) + 1); } } let maxGap = 0; map.forEach((key) => { maxGap = Math.max(maxGap, key); }) return wall.length - maxGap; };