zoukankan      html  css  js  c++  java
  • leetcode------Container With Most Water

    标题: Container With Most Water
    通过率: 31.9%
    难度: 中等

    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.

    本题就是找一个最大面积的长方形,公式就是 min(h(l),h(r))*(r-l)

    那么肯定是从两头往里面找,如:

    若h(l)<h(r)时就从头开始找到一个比h(l)大的,然后计算一次,

    反之则从后面找到一个比h(r)大的再计算一次,

    每次计算都要更新一次result,最后的result一定是最大的

    代码如下:

     1 public class Solution {
     2     public int maxArea(int[] height) {
     3         int l=0,r=height.length-1,result=0;
     4         while(l<r){
     5             result=Math.max(result,Math.min(height[l],height[r])*(r-l));
     6             if(height[l]<height[r]){
     7                 int k=l;
     8                 while(k<r&&height[k]<=height[l]){
     9                     k++;
    10                 }
    11                 l=k;
    12             }
    13             else{
    14                 int k=r;
    15                 while(k>l&&height[k]<=height[r]){
    16                     k--;
    17                 }
    18                 r=k;
    19             }
    20         }
    21         return result;
    22     }
    23 }
  • 相关阅读:
    设计模式:访问者模式
    设计模式:解释器模式
    设计模式:享元模式
    设计模式:中介者模式
    设计模式:职责链模式
    设计模式:命令模式
    设计模式:桥接模式
    设计模式:单例模式
    设计模式:迭代器模式
    设计模式:组合模式
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4317644.html
Copyright © 2011-2022 走看看