题解 | #接雨水问题#
接雨水问题
http://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f
我的解法是一层一层的解,但是不知道为啥就是耗时的不得了
逻辑是柱子序号入栈,当发现比栈顶大时出栈,出栈的做桶底,如果出空了就不处理,
如果出完栈里还有值就按当前值跟栈顶其较小,减去桶底后乘以宽度。
public long maxWater(int[] arr) { // write code here //栈里存序号 Stack<Integer> indexs = new Stack<>(); Long res = 0L; for (int i = 0; i < arr.length; i++) { int cur = arr[i]; if (indexs.isEmpty()) { indexs.add(i); } else { if (cur == arr[indexs.peek()]) continue; while (!indexs.isEmpty()) { if (cur < arr[indexs.peek()]) {//不保存重复 indexs.add(i); break; } else { int left = indexs.pop(); int floor = arr[left]; if (indexs.isEmpty()) { indexs.add(i); break; } int trueHeight = Math.min(cur - floor, arr[indexs.peek()] - floor); int w = i - indexs.peek() - 1; res += Long.parseLong(trueHeight + "") * Long.parseLong(w + ""); } } } } return res; }