Trapping Rain Water

mac2022-06-30  38

Description:

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

Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

Solution:

class Solution { public: /** * @param heights: a vector of integers * @return: a integer */ int trapRainWater(vector<int> &heights) { auto sz = (int)heights.size(); if (sz < 3) return 0; int l = 0, r = sz-1, left = heights[l], right = heights[r]; int rc = 0; while (l < r) { if (left < right) { ++l; if (heights[l] < left) rc += left-heights[l]; else left = heights[l]; } else { --r; if (heights[r] < right) rc += right-heights[r]; else right = heights[r]; } } return rc; } };

转载于:https://www.cnblogs.com/deofly/p/trapping-rain-water.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)