题解 | #接雨水问题#

接雨水问题

http://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f

//C++三指针解决接雨水问题

class Solution {
public:
    /**
     * max water
     * @param arr int整型vector the array
     * @return long长整型
     */
    long long maxWater(vector<int>& arr) {
        // write code here
        int top=0;
        for(int i=0;i<arr.size();i++){
            if(arr[i]>arr[top])
                top=i;
        }
        int left=0;
        int right=0;
        long long water=0;
        while(right<top){
            if(arr[left]>arr[right])
            {
                water=water+arr[left]-arr[right];
                right+=1;
            }else{
                left=right;
                right+=1;
            }
        }
        left=arr.size()-1;
        right=arr.size()-1;
        while(right>top){
            if(arr[left]>arr[right])
            {
                water=water+arr[left]-arr[right];
                right-=1;
            }else{
                left=right;
                right-=1;
            }
        }
        return water;
    }
};
全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务