
问题
给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
输入: [1,8,6,2,5,4,8,3,7]
输出: 49
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 and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
示例
public class Program { public static void Main(string[] args) { var height = new int[] { 1, 8, 6, 2, 5, 4, 8, 3, 7 }; var res = MaxArea(height); Console.WriteLine(res); height = new int[] { 5, 7, 2, 0, 9, 1, 5, 16, 25, 36 }; res = MaxArea2(height); Console.WriteLine(res); Console.ReadKey(); } public static int MaxArea(int[] height) { //暴力法 var max = 0; for(var i = 0; i < height.Length; i++) { for(var j = i + 1; j < height.Length; j++) { max = Math.Max(max, Math.Min(height[i], height[j]) * (j - i)); } } return max; } public static int MaxArea2(int[] height) { //双指针法 var max = 0; var left = 0; var right = height.Length - 1; while(left < right) { max = Math.Max(max, Math.Min(height[left], height[right]) * (right - left)); //“木桶”左右板短的那边向中心移动 if(height[left] < height[right]) left++; else right--; } return max; } }
以上给出2种算法实现,以下是这个案例的输出结果:
49 56
分析:
显而易见,MaxArea 的时间复杂度为: ,MaxArea2 的时间复杂度为:
。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/3615。