lc 接雨水

链接:https://leetcode-cn.com/problems/trapping-rain-water/

代码:

class Solution {
public:
    
    int trap(vector<int>& height) {
        int n = height.size();
        if(n == 0 || n == 1) return 0;
        int ans = 0;
        for(int i = 1; i <= n-2; i++) {
            int max_left, max_right = INT_MIN;
            for(int j = i; j >= 0; j--) {
                if(height[j] >= max_left) {
                    max_left = height[j];
                }
            }
            for(int j = i; j < n; j++) {
                if(height[j] >= max_right) {
                    max_right = height[j];
                }
            }
            ans += min(max_left, max_right) - height[i];
        }
        return ans;
    }
};
View Code

思路:对于每一个点向左找最高点,向右找最高点,取一个最小值减去 height[i]即可。

posted on 2020-05-23 00:14  FriskyPuppy  阅读(84)  评论(0编辑  收藏  举报

导航