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

来源:互联网 发布:网盘 数据库 编辑:程序博客网 时间:2024/06/18 01:00

题目

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;    }
原创粉丝点击