标签:style blog http color for c
https://oj.leetcode.com/problems/trapping-rain-water/
模拟题,计算出在凹凸处存水量。
对于一个位置 i ,分别计算出它左边的最大值 left (从左扫描一遍), 右边的最大值 right(从右扫描一遍) 。找left right中的最小值,如果大于 A[i],则做 min - A[i] 的累加。
class Solution { public: int trap(int A[], int n) { if(n<=1) return 0; vector<int> leftHigher; vector<int> rightHigher; int leftLarge = 0, rightLarge = 0; for(int i = 0;i<n;i++) { if(A[i]>leftLarge) leftLarge = A[i]; leftHigher.push_back(leftLarge); } rightHigher.resize(n); for(int j = n-1;j>=0;j--) { if(A[j]>rightLarge) rightLarge = A[j]; rightHigher[j] = rightLarge; } int sum = 0; for(int i = 0;i<n;i++) { int min = leftHigher[i]<rightHigher[i]?leftHigher[i]:rightHigher[i]; if(min>A[i]) sum += min - A[i]; } return sum; } };
LeetCode OJ-- Trapping Rain Water*,布布扣,bubuko.com
LeetCode OJ-- Trapping Rain Water*
标签:style blog http color for c
原文地址:http://www.cnblogs.com/qingcheng/p/3797808.html