diff --git a/.idea/workspace.xml b/.idea/workspace.xml index f51d5d1..9b66a1a 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,9 +2,8 @@ - + - - - - @@ -339,7 +345,8 @@ - @@ -354,62 +361,62 @@ - + - + - + - - - + + + - - - + + + - - - + + + - - - + + + - + - + - + - + - + - + - + - + - + diff --git a/src/q42/Solution.java b/src/q42/Solution.java new file mode 100644 index 0000000..9d7adda --- /dev/null +++ b/src/q42/Solution.java @@ -0,0 +1,27 @@ +package q42; + +/** + * 暴力法o(n^2) 找出每个元素(柱子)上面的水量,可提前存储最大高度数组(两个左和右),最后遍历一次优化为o(n) + */ +public class Solution { + + public int trap(int[] height) { + int ans = 0; + int size = height.length; + for (int i = 1; i < size - 1; i++) { + int maxLeft = 0, maxRight = 0; + for (int j = i; j >= 0; j--) { + maxLeft = Math.max(maxLeft, height[j]); + } + for (int j = i; j < size; j++) { + maxRight = Math.max(maxRight, height[j]); + } + ans += Math.min(maxLeft, maxRight) - height[i]; + } + return ans; + } + + public static void main(String[] args) { + new Solution().trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}); + } +}