leetcode 11. Container With Most Water

来源:互联网 发布:node gzip压缩 编辑:程序博客网 时间:2024/06/04 00:48

java 实现
题目:
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.

public class Solution {    public int maxArea(int[] height) {        int len=height.length;        if(len==2){            if(height[0]<=height[1])            return height[0];            else                return height[1];        }        int i=0;        int begin=0;        int end=len-1;        int min=height[begin]>height[end]?height[end]:height[begin];        int maxnum=(len-1)*min;        int tl=begin,tr=end;         while(begin<end){            int temp=(end-begin)*(height[begin]>height[end]?height[end]:height[begin]);            tl=begin;            tr=end;             if(temp>maxnum){                  maxnum=temp;              }            if(height[begin]<height[end]){                do{                    tl++;                }while(tl<height.length && height[tl]<=height[begin]);                begin=tl;            }else{                do{                      tr--;                  }while(tr>=0 && height[tr]<=height[end]);                  end=tr;            }        }        return maxnum;    }}
0 0
原创粉丝点击