[LeetCode]042-Trapping Rain Water
2015-12-29 19:06
495 查看
题目:
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.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Solution:
思路,先找到最高的点,然后两边处理。举例左边的情况:
设置两个指针i,j。i往中间最高点移动,若height[i] >=height[j]。则计算j和i之间的可存放空间,并将j移动到i的位置:j=i,i继续往后移动,直到最高点。右边的处理情况类似。
代码如下:
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.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Solution:
思路,先找到最高的点,然后两边处理。举例左边的情况:
设置两个指针i,j。i往中间最高点移动,若height[i] >=height[j]。则计算j和i之间的可存放空间,并将j移动到i的位置:j=i,i继续往后移动,直到最高点。右边的处理情况类似。
代码如下:
class Solution { public: int trap(vector<int>& height) { int n = height.size(); int i,j,k; int sum = 0; int h = 0; int max = 0; for(i =0;i<n;i++) { if(height[i] > max) { max = height[i]; h = i; } } i = 0; j = i+1; while(i<=h && j <=h) { if(height[i] >= height[j]) { sum += calculate(height,j,i); j = i; } i++; } j=n-1; i = j-1; while(i >= h) { if(height[i] >= height[j]) { sum += calculate(height,i,j); j = i; } i--; } return sum; } int calculate(vector<int> height,int begin,int end) { int h = min(height[begin],height[end]); int w = end - begin-1; int area = h * w; for(int i = begin+1;i<end;i++) { area -= height[i]; } return area<0?0:area; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解