LeetCode Online Judge 题目C# 练习 - Trapping Rain Water
2012-10-22 22:21
344 查看
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.
代码分析:
这是我一开始复习就在别人的面经上看到的题,数数手指也快2年了,唉。。。。什么时候才能给我OFFER啊??
1. 找到最高的index
2. 从左往右算water 的体积(面积)。p = 0, 如果A[i] < A[p],差值就可以承载水,如果A[i] >= A[p] ,p = i
3. 从右往左在加一次water。 同理。
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
public static int TrappingRainWater(int[] A) { if (A.Length <= 2) return 0; int h = 0; // find the highest index for (int i = 0; i < A.Length; i++) { if (A[i] > A[h]) h = i; } int water = 0; int p = 0; // calculate from left to highest for (int i = 1; i < h; i++) { if (A[p] > A[i]) water += A[p] - A[i]; else p = i; } p = A.Length - 1; // calculate from right to highest for (int i = A.Length - 2; i > h; i--) { if (A[p] > A[i]) water += A[p] - A[i]; else p = i; } return water; }
代码分析:
这是我一开始复习就在别人的面经上看到的题,数数手指也快2年了,唉。。。。什么时候才能给我OFFER啊??
1. 找到最高的index
2. 从左往右算water 的体积(面积)。p = 0, 如果A[i] < A[p],差值就可以承载水,如果A[i] >= A[p] ,p = i
3. 从右往左在加一次water。 同理。
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Longest Valid Parentheses
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List
- LeetCode Online Judge 题目C# 练习 - Sort Color
- LeetCode Online Judge 题目C# 练习 - Unique Paths II
- LeetCode Online Judge 题目C# 练习 - Merge Two Sorted Lists
- LeetCode Online Judge 题目C# 练习 - Jump Game II
- LeetCode Online Judge 题目C# 练习 - Letter Combinations of a Phone Number
- LeetCode Online Judge 题目C# 练习 - Remove Nth Node From End of List
- LeetCode Online Judge 题目C# 练习 - Valid Parentheses
- LeetCode Online Judge 题目C# 练习 - Combination Sum II
- LeetCode Online Judge 题目C# 练习 - Longest Common Prefix
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List II
- LeetCode Online Judge 题目C# 练习 - Rotate Image
- LeetCode Online Judge 题目C# 练习 - Search a 2D Matrix
- LeetCode Online Judge 题目C# 练习 - Balanced Binary Tree
- LeetCode Online Judge 题目C# 练习 - Longest Palindromic Substring
- LeetCode Online Judge 题目C# 练习 - Minimum Path Sum
- LeetCode Online Judge 题目C# 练习 - N-QueensII
- LeetCode Online Judge 题目C# 练习 - Partition List