leetcode 11 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.

输入一个数组,数组的每个元素都表明了一条垂直的线,其中每个元素的位置表明横坐标,元素的值表明纵坐标。咱们须要找出这些线所围成的“容器”,能装最多水的水量。数组

想法

  • 由于这是一个装水的容器,因此并不能直接的算围成的面积,装水的面积取决于两条线中较短的那条的长度和两条线之间横坐标的差值。
  • 这道题是不能用蛮力法解决的,会超时T^T。
  • 这个解法想法是这样的,咱们用两个变量start,end指向数组的起始元素和末尾元素。首先计算这两条线所围成的容器面积,而后移动指向较短的线段的指针。直到start = end。

解法

public int maxArea(int[] height) {
        int maxArea = 0;
        int start = 0;
        int end = height.length-1;
        
        while(start < end){
            maxArea = Math.max(maxArea, Math.min(height[start], height[end])*(end-start));
            if(height[start] < height[end]) start ++;
            else end--;
        }
        
        return maxArea;
    }
相关文章
相关标签/搜索