美文网首页
2 Pointers

2 Pointers

作者: MrWheat | 来源:发表于2018-07-30 10:59 被阅读0次

    2 Pointers

    Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
    Example:
    Input: [0,1,0,2,1,0,1,3,2,1,2,1]
    Output: 6

    int trap(vector<int>& height)
    {
        int left = 0, right = height.size() - 1;
        int ans = 0;
        int left_max = 0, right_max = 0;
        while (left < right) {
            if (height[left] < height[right]) {
                height[left] >= left_max ? (left_max = height[left]) : ans += (left_max - height[left]);
                ++left;
            }
            else {
                height[right] >= right_max ? (right_max = height[right]) : ans += (right_max - height[right]);
                --right;
            }
        }
        return ans;
    }
    

    注意:使用两个指针逼近,经典的链表问题:https://www.cnblogs.com/dancingrain/p/3405197.html

    相关文章

      网友评论

          本文标题:2 Pointers

          本文链接:https://www.haomeiwen.com/subject/ksmxvftx.html