Container With Most Water-Leetcode

来源:互联网 发布:淘宝一楼土木人可靠吗 编辑:程序博客网 时间:2024/05/17 10:26

Question :

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.


Solution :

一开始的想法是两层遍历,找出所有可能,时间复杂度是O(n^2)。

然后思考怎样改进,

里面有哪些是无效的计算,

最大水容量是由两根线中较短的那根和x轴的距离决定的,

比如第一个线和最后一根线, 最后一根线比第一根长, 那么最后一根向第一根往前的遍历就没有意义了,因为较短的一根是第一根,再往前遍历只能是较短的一根更短,x轴距离更小,水容量更小。

所以设置初始为第一根和最后一根的标志,更小的一根往中间移动,这样的时间复杂度为O(n)

Java 代码:

public class Solution {public int maxArea(int[] height) {        int i = 0, j = height.length - 1;int MostWater = Math.min(height[i], height[j]) * (j - i);while (i < j) {if (height[i] > height[j]) {j --;} else {i ++;}MostWater = Math.max(MostWater, Math.min(height[i], height[j]) * (j - i));}return MostWater;    }}




原创粉丝点击