42. Trapping Rain Water

题目来源:
 
自我感觉难度/真实难度:
 
题意:
 
分析:
 
自己的代码:
class Solution:
    def trap(self, height: List[int]) -> int:
        a,b=0,len(height)-1
        leftMax,rightMax=0,0
        res=0
        while a<=b:
            if leftMax<=rightMax:
                if height[a]>=leftMax:
                    leftMax=height[a]
                else:
                    res+=(leftMax-height[a])
                a+=1
            else:
                if height[b]>=rightMax:
                    rightMax=height[b]
                else:
                    res+=(rightMax-height[b])
                b-=1
        return res
            
代码效率/结果:
 
优秀代码:
class Solution {
public:
    int trap(int A[], int n) {
        int left=0; int right=n-1;
        int res=0;
        int maxleft=0, maxright=0;
        while(left<=right){
            if(A[left]<=A[right]){
                if(A[left]>=maxleft) maxleft=A[left];
                else res+=maxleft-A[left];
                left++;
            }
            else{
                if(A[right]>=maxright) maxright= A[right];
                else res+=maxright-A[right];
                right--;
            }
        }
        return res;
    }
};

 

代码效率/结果:

 
自己优化后的代码:
 
反思改进策略:

1.思考的时候,涉及比较的问题,一定要考虑多指针。

 

写题时间时长:

2hour

posted @ 2019-03-07 20:20  dgi  阅读(188)  评论(0编辑  收藏  举报