【数组】Container With Most Water

来源:互联网 发布:科学管理案例 知乎 编辑:程序博客网 时间:2024/05/01 17:59

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

题意:从数组中找出两个值作为蓄水池的两个边,当然高度由矮的边决定

解法:使用两个指针,分别指向数组的两端,移动短边的指针

public class Solution {    public int area(int []a, int i, int j){        return Math.min(a[i], a[j]) * (j - i);    }        public int maxArea(int[] height) {        int len = height.length;        if(len <= 1) return 0;                int l = 0, r = len-1;        int max = 0;        while(l < r){            max = Math.max(max, area(height, l ,r));                        if(height[l] < height[r]) l++;            else r--;        }        return max;    }}


0 0