LeetCode 42 | 刷题打卡

标题描绘

给定 n 个非负整数标明每个宽度为 1 的柱子的高度图,核算按此摆放的柱子,下雨之后能接多少雨水。
LeetCode|掘金酱打卡应战

标题链接: LeetCode

示例1:

输入:height = [0,1,0,2,1,0,1,3,2,1数组指针,2,1]
输出:6
解说:上面是由LeetCode数组 [0,1,0,2,1,0,1,3,2数组词,1,2,1] 标明的高度图,在这种情况下,能够接 6 个单位的雨水(蓝色部分表leetcode中文官网明雨水)。

示例2:

输入:height = [4,2,0,3,2,5]
输出:9
  • n == he数组去重ight.length
  • 0 <= n <= 3 * 10^4
  • 0 <= height[i] <= 10^5

思路分析

  • 主意1

接雨水的量取决于每根柱子左右最高的柱子,所以思路很简单就leetcode官网是每根柱子遍历数组去重的5种方法一遍向左右查找然后把水深加起来,但考虑到时间复杂度太高数组去重我没有这样写(这道题n取值不会太大暴力办法也能够过)

代码数组初始化:

class Solution {
puleetcode是干什么的blic:
int min(int a,int b){
if(a<b){
return a;
}
else{
return b;
}数组排序
};
int max(int a,int b){
if(a<b){
return b;
}
else{
return a;
}
};数组
intleetcode和牛客网区别 trap(vector<int>& height) {
int n = height.size();
ifleetcode高频100题 (n < 3) return 0;//长度小于3不可能装水
int sum = 0;
for (int i = 1; i < n - 1; i++) {
int num = height[i];
int left = 0;
fleetcode怎样刷题or (int j = i - 1; j >=leetcode和牛客网区别 0; j--)
left = max(left,heightleetcode中文官网[j]);
if (left <= num) continue;
int right = 0;
for (int j = i + 1; j < n; j++)
right = max(rleetcode怎样刷题ileetcode是干什么的ght,height[j]);
if (right <= num) continue;
sum += min(left, right) - num;
}
return sum;
}
};

LeetCode|掘金酱打卡应战

  • 主意2

既然上面一个主意leetcode刷题指南也提到了装水需求左右都高于当时的数组排序柱子,那设两个节点,从数组两端开始是不是只需便历一遍的一同核算装水的量呢?

  • 首要定义两个变量分别为树组的第一位和终究一位leetcode中文官网,它们分别以不同的方向跋涉

  • 当某一边比另数组词一边高的时候就让另一边先跋涉

  • 跋涉时遇到比其数组去重时矮的柱子就装进雨水填平,一同记载雨数组排序

    图片示例:

    LeetCode|掘金酱打卡应战

    代码:

        clasLeetCodes Solution {
    publ数组去重的5种方法i数组去重的5种方法c:
    int trap(vector数组初始化<int>& height) {
    int sum=0;
    int l=0,r=height.size()-1;
    while(l<r){
    if(height[l]<数组指针=height[r]){
    if(height[l]<=height[l+1]){
    l++;
    //continue;
    }else{
    sum+=height[l]-height[l+1];
    height[l+1]=height[l];
    l++;
    }
    }
    else{
    if(height[r]<=height[r-1]){
    r--;
    //continLeetCodeue;
    }else{
    sum+=height[r]-height[r-1];
    height[r-1]=height[r];
    r--;
    }
    }QAQ
    }
    return sum;
    }
    };
    

LeetCode|掘金酱打卡应战

良久leetcode高频100题没写C了过了仍是很高兴的QAQ