java 实现Leetcode Container With Most Water

来源:互联网 发布:淘宝衣服有瑕疵 编辑:程序博客网 时间:2024/05/08 07:14

java 实现Leetcode 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.
简单点说就是:
数据两边的值所对应的垂直于X轴的竖线和中间的X轴形成类似于一个没盖子的水缸,水缸的高度是两边竖线中较短的一个。
结题思路:
左右两边指针往中间靠拢,那边的数据比较小,那边的指针就往中间移动一位。
代码实现如下:

/** * 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. * <p> * Note: You may not slant the container. */public class ContainerWithMostWater {    public int maxArea(int[] height) {        // TODO 左边比右边高,右边往中间移动一点        // TODO 右边比左边高,左边往中间移动一点        int pointLeft = 0, pointRight = height.length - 1, maxValue = 0;        while (pointLeft < pointRight) {            maxValue = Math.max(maxValue, Math.min(height[pointLeft], height[pointRight]) * (pointRight - pointLeft));            if (height[pointLeft] > height[pointRight]) {                pointRight--;            } else {                pointLeft++;            }        }        return maxValue;    }}

至此,OVER!!!

0 0