[LeetCode]554. Brick Wall

来源:互联网 发布:java transaction 编辑:程序博客网 时间:2024/05/29 17:13

https://leetcode.com/problems/brick-wall/#/description


一个二维的墙,找出一条int位置的竖线,能穿过最少的墙




反向思考,找出空隙最多的index,而不是找墙最少的index,否则有可能超内存

public class Solution {    public int leastBricks(List<List<Integer>> wall) {        if (wall == null) {            return 0;        }        HashMap<Integer, Integer> map = new HashMap();        int cnt = 0;        for (List<Integer> w : wall) {            int idx = 0;            for (int i = 0; i < w.size() - 1; i++) {                idx += w.get(i);                map.put(idx, map.getOrDefault(idx, 0) + 1);                cnt = Math.max(map.get(idx), cnt);            }        }        return wall.size() - cnt;    }}


原创粉丝点击