LeetCode 41. Trapping Rain Water O(n)实现

参考了hackersun007的题解


对于每个A[i], 若它两边的最高高度满足min(leftmost[i], rightmost[i]) > A[i], 则坐标i上对应的水的横截面积为 min(leftmost[i], rightmost[i]) - A[i]


从左到右遍历A[], 求出leftmost数组;

反向遍历A[], 求出rightmost. 

最后利用leftmost[], rightmost[], 遍历A[]求出水的横截面总面积。


代码:

class Solution 
{
public:
    int trap(int A[], int n) 
    {
    	int sum = 0;
		vector<int> leftmost(n, 0), rightmost(n, 0);

		for (int i = 0, maxx = 0; i < n; ++ i)
		{
			leftmost[i] = maxx;
			maxx = maxx>A[i]? maxx: A[i];
		}
		for (int i = n-1, maxx = 0; i >= 0; -- i)
		{
			rightmost[i] = maxx;
			maxx = maxx>A[i]? maxx: A[i];
		}
		for (int i = 1; i < n-1; ++ i)
		{
			if (min(leftmost[i], rightmost[i]) > A[i])
			{
				sum += min(leftmost[i], rightmost[i]) - A[i];
			}
		}

		return sum;
    }
};


你可能感兴趣的:(LeetCode,C++)