标签:
Given n non-negative integers representing an elevation map where the width of each bar is 1, computehow much water it is able to trap after raining.
For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
对于每个柱子,找到其左右两边最高的柱子,该柱子能容纳的面积就是 min(max_left,max_right) - height。所以,
1. 从左往右扫描一遍,对于每个柱子,求取左边最大值;
2. 从右往左扫描一遍,对于每个柱子,求最大右值;
3. 再扫描一遍,把每个柱子的面积并累加。
/*trapping train water v2*/ int trap(vector<int> &height) { int result=0; int n = height.size(); int *left_flag = new int[n]; int *right_flag = new int[n]; memset(left_flag, INT_MAX, n*sizeof(int)); memset(right_flag, INT_MAX, n* sizeof(int)); left_flag[0] = 0; right_flag[n - 1] = 0; //扫描左边 for (int i = 1; i < n; i++) { if (height[i - 1]>left_flag[i - 1]) { left_flag[i] = height[i - 1]; } else { left_flag[i] = left_flag[i - 1]; } } //扫描右边 for (int i = n - 2; i >= 0; i--) { if (height[i + 1] > right_flag[i + 1]) right_flag[i] = height[i + 1]; else right_flag[i] = right_flag[i + 1]; } for (size_t i = 0; i < n; i++) { int compare = min(left_flag[i], right_flag[i]) - height[i]; result += (compare>0 ? compare : 0); } delete[] left_flag; delete[] right_flag; return result; }相关题目: (M) Container With Most Water
Product of Array Except Self
标签:
原文地址:http://www.cnblogs.com/panweishadow/p/4781427.html