#11 Container With Most Water

Description

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.

Example

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

解题思路

这道题就是找两条垂直线和坐标x轴构成的最大区域,一般来说最常见的想法就是遍历所有可能性然后找到最大值,时间复杂度O(n2),代码如下:

class Solution {
    public int maxArea(int[] height) {
        int i, j;
        int max = 0, temp = 0;;
        for(i = 0; i < height.length; i++){
            for(j = 0; j < i; j++){
                int l = i - j; 
                int h = height[i] > height[j]? height[j]: height[i];
                temp = h * l;
                if(temp > max)
                    max = temp;
            }
        }
        return max;
    }
}

非常耗时,215ms……
然后题目有给出一个solution说可以先取x轴上距离最长的两条垂直线段求max area,然后每次移动较短的那根垂直线来起到更新数据的效果,其实也比较好理解,因为当只有移动了较短边才有可能得到比初始情况下更大的范围(在x已经减少的情况下,需要增加height才有可能得到更大的max area),这样时间复杂度只是O(n),耗时5ms

class Solution {
    public int maxArea(int[] height) {
        int i = 0, j = height.length - 1;
        int n = j - i;
        int max = 0, temp = 0;
       while(true){
            int l = j - i; 
            int h1 = height[i];
            int h2 = height[j];
            int h = h1 > h2? h2: h1;
            temp = h * l;
            if(temp > max)
                max = temp;
            if(h1 > h2)
                j--;
            else
                i++;
           n = j - i;
           if(n < 1)
               break;
        }
        return max;
    }
}

其他

终于放假了有点小开心
考试周真的会死人的
代码素养还是要加强……很多想法不看solution就想不到这样不行……
希望可以在寒假好好的刷leetcode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值