LeetCode 11. Container With Most Water

来源:互联网 发布:网络在线直播 编辑:程序博客网 时间:2024/06/07 11:21

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

Subscribe to see which companies asked this question.


一个整数数组,序号代表底,数组值表达高度,找到一个能装最多水的情况。

能想到最好的办法是o(n)的,两个指针一个从数组头向尾部走,另一个从尾部往头部走。没走一步做两个对比:

1.当前的面积和max比是否更大,更大则替换max值;

2.比较两个指针谁更小,小的向中间走一步;原因是小的不会得到更高的值(它的高度就是限制)

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


0 0
原创粉丝点击