leetcode 数组Ⅲ 2021-02-19
接雨水(困难)1
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
示例 1:
输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
输出:6
解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
示例 2:
输入:height = [4,2,0,3,2,5]
输出:9
思路:找出最高点
分别从两边往最高点遍历:如果下一个数比当前数小,说明可以接到水
private static int trap(int[] height) {
int result = 0;
int maxHeight = Integer.MIN_VALUE;
int maxIndex = 0;
for (int i = 0; i < height.length; i++) {
if (height[i] > maxHeight) {
maxHeight = height[i];
maxIndex = i;
}
}
int start = 0;
for (int i = 0; i < maxIndex; i ++ ) {
if (height[start] > height[i + 1]) {
result += (height[start] - height[i + 1]);
} else{
start = i + 1;
}
}
start = height.length - 1;
for (int i = height.length - 1; i > maxIndex; i -- ) {
if (height[start] > height[i - 1]) {
result += (height[start] - height[i - 1]);
} else{
start = i - 1;
}
}
return result;
}
//暴力解法 超时
public int trapA(int[] height) {
if (height.length == 0) {
return 0;
}
int result = 0;
Map<Integer, Integer> map = new HashMap<>();
Map<Integer, Integer> first = new HashMap<>();
Map<Integer, Integer> last = new HashMap<>();
for (int i = 0; i < height.length; i++) {
map.put(height[i], 1);
for (int x = 1; x <= height[i]; x++) {
if (!first.containsKey(x)) {
first.put(x, i);
}
last.put(x, i);
}
}
int[] nums = new int[height.length];
System.arraycopy(height, 0, nums, 0, height.length);
Arrays.sort(height);
for (int i = 1; i <= height[height.length - 1]; i++) {
for (int j = first.get(i) + 1; j < last.get(i); j++) {
if (nums[j] < i) {
result++;
}
}
}
return result;
}
数组标签完成度
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-sightseeing-pair
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ↩︎