您的位置:首页 > 大数据 > 人工智能

No.011:Container With Most Water

2016-10-09 10:07 183 查看

问题:

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.

 

官方难度:

Medium

 

翻译:

给定n个非负整数a1,a2,...,an,每一个数值代表坐标轴上的坐标(i,ai)。

画上n条垂直于横坐标的竖线,用于连接点(i,ai)和(i,0)。找到两条线,与x轴一起形成一个容器,能够容纳最多的水。

注意容器不能倾斜。

 

方法一:

  1. 利用一个二次循环,同时维护一个最大面积max。

 

方法一的解题代码:

1     public static int maxArea(int[] height) {
2         if (height == null || height.length < 2) {
3             throw new IllegalArgumentException("Input error");
4         }
5         // 初始面积
6         int left = 0, right = height.length - 1;
7         int area = (right - left) * Math.min(height[left], height[right]);
8         // 左右侧开始的最长高度
9         int leftMax = height[left];
10         int rightMax = height[right];
11         // 从两侧向中间夹逼,即底在不断变小
12         while (left < right) {
13             if (height[left] < height[right]) {
14                 left++;
15                 // 更小的高没有比较价值
16                 if (height[left] <= leftMax) {
17                     continue;
18                 } else {
19                     leftMax = height[left];
20                 }
21                 area = Math.max(area, (right - left) * Math.min(height[left], height[right]));
22             } else {
23                 right--;
24                 if (height[right] <= rightMax) {
25                     continue;
26                 } else {
27                     rightMax = height[right];
28                 }
29                 area = Math.max(area, (right - left) * Math.min(height[left], height[right]));
30             }
31         }
32         return area;
33     }
maxArea

 

相关链接:

https://leetcode.com/problems/container-with-most-water/

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/medium/Q011.java

 

PS:如有不正确或提高效率的方法,欢迎留言,谢谢!

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: