LeetCode-array-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.

意思是,有一个非负数的数组,数组中每个元素就是一条垂直的线,这条线的两端坐标是(i,ai),( i,0),i是数组元素的下标,
选取两条组成面积最大的,计算出值,注意,矩形不能倾斜,,,


1499077569(1).jpg

如上图。
从java代码解决,直接上代码

/**
 * Created by Wangjianxin on 2017/7/3 0003.
 */
public class ContainerWithMostWater {

    public int maxArea(int[] height) {
        int oldmax = 0;  
        int newmax = 0;
        int len = height.length;

        int left = 0;
        int right = len - 1;

        while (left < right){ 
            //计算面积,看上图可以知道,需要两条线中短线的高,和两线之间的距离宽
            if(height[left] > height[right]){ 
                oldmax = height[right] * (right - left);
            }else {
                oldmax = height[left] * (right - left);
            }

            if(newmax < oldmax){
                newmax = oldmax; //得到最大值
            }
            //这里用于从两头往中间一直计算,只要两条线中壹条短一些, 就应该在那条短的线继续向前或者向后的其他线在计算
            if(height[left] > height[right]){
                right --;
            }else {
                left ++;
            }

        }
        return newmax;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容