leetcode解题方案--011--Container With Most Water

题目

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.

例如 8 4 9 6 3 7 1 应为8和7组成的容器,答案为35.

分析

暴力解法:这种思想很想求直方图下方最大矩形面积。直方图的思想是以每个ai为最低点,求出左侧边界和右侧边界,对每一项算出其面积,再取最大。
这道题的想法就是,以每个a[i]为边界中较短的那一条边。求最大面积,就是从0开始找到大于等于a[i]的,再从length-1开始找到第一个大于等于a[i]的。两者取最大。最后,在所有的面积中取最大。
此方法会超时

代码块

 public static int maxArea0(int[] height) {
        int[] result = new int[height.length];
        int max = 0;
        int length = height.length;
        for (int i = 0; i <length; i++) {
            int left = 0;
            int right = 0;
            for (int k1 = 0; k1 < i; k1++) {
                if (height[k1] >= height[i]) {
                    left = height[i]*(i-k1);
                    break;
                }
            }
            for (int k2 = length-1; k2 > i; k2--) {
                if (height[k2] >= height[i]) {
                    right = height[i]*(k2-i);
                    break;
                }
            }
            int tmp = left>right?left:right;
            if (tmp>max) {
                max = tmp;
            }
        }
        return max;

分析

用两个指针从两端开始向中间靠拢,如果左端线段短于右端,那么左端右移,反之右端左移,知道左右两端移到中间重合,记录这个过程中每一次组成木桶的容积,返回其中最大的。

 public static int maxArea1(int[] height) {
        int max = 0;
        int length = height.length;

        for (int i =0, j = length-1; j-i>=1;) {
            if (height[j] >=height[i]) {
                int tmp = height[i] * (j-i);
                if (max < tmp) {
                    max = tmp;
                }
                i++;
            }else {
                int tmp = height[j] * (j-i);
                if (max < tmp) {
                    max = tmp;
                }
                j--;
            }
        }
        return max;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值