LeetCode Online Judge 题目C# 练习 - Container With Most Water
2012-08-29 05:00
549 查看
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
代码分析:
建两个指针分别从两端往中间靠拢, 算出面积,如果比之前最大的面积大,就替换max_area变量。
Note: You may not slant the container.
public static int MaxArea(int[] height) { int a = 0; //建立a指针指向最左端 int b = height.GetUpperBound(0); //建立b指针指向最右端 int max_area = 0; while (a < b) //当a还在b的左边 { int curr_area = Math.Min(height[a], height[b]) * (b - a); //计算当前 a , b 与x轴围起来的面积 max_area = curr_area > max_area ? curr_area : max_area; //如果当前面积比max_area打,替换之 if (height[a] > height[b]) //如果 height[a] > height[b],b往左移 { while (height[--b] < height[b]); //直到找到b的上升沿,因为,如果是下降沿,面积一定没之前大 } else //如果 height[a] <= height[b],a往左移 { while (height[++a] < height[a]) ; //直到找到a的上升沿,因为,如果是下降沿,面积一定没之前大 } } return max_area; }
代码分析:
建两个指针分别从两端往中间靠拢, 算出面积,如果比之前最大的面积大,就替换max_area变量。
相关文章推荐
- Leetcode练习 #11 Container With Most Water
- LeetCode Online Judge 题目C# 练习 - Substring with Concatenation of All Words
- leetcode做题总结,题目Container With Most Water------ 2012/01/08
- leetcode -- Container With Most Water -- 经典题目重要!
- [LeetCode] Container With Most Water
- [leetcode] Container With Most Water
- [LeetCode] Container With Most Water
- [leetcode] Container With Most Water
- Container With Most Water - LeetCode
- LeetCode Online Judge 题目C# 练习 - Binary Tree Level Order Traversal
- [LeetCode] Container With Most Water, Solution
- 7_leetcode_container with most water
- LeetCode--Container With Most Water
- [leetcode]Container With Most Water
- leetcode - Container With Most Water
- LeetCode 141 Container With Most Water
- leetcode---container-with-most-water---数组
- [Leetcode]Container With Most Water
- LeetCode 11 Container With Most Water
- 数据结构与算法[LeetCode]—Container With Most Water