zoukankan      html  css  js  c++  java
  • leet_11

    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.

    n个非负的整数,a1,a2....an, 每一个都代表了一个坐标(i, ai). n条从点(i,ai) 到(i, 0)这样的垂直线。找到这样的两条线,和x轴形成一个容器,可以包含最多的水。

     
    public static int maxArea(int[] height) {

    if(null == height){
    return 0;
    }
    int size = height.length;
    int maxS = 0;

    for(int i = 0; i < size; i++){
    for(int j = i + 1;j < size; j++){
    int maxSTemp = Math.min(height[i], height[j]) * (j - i);
    if(maxSTemp > maxS){
    maxS = maxSTemp;
    }
    }
    }

    return maxS;
    }

    public static int maxArea2(int[] height){

    int max = 0;
    int i=0, j=height.length-1;
    while(i <= j){
    int area = (j-i)*Math.min(height[i], height[j]);
    max = Math.max(max, area);
    if(height[j] >= height[i]){
    i++;
    }else{
    j--;
    }
    }

    return max;
    }
     

    Analysis

    Initially we can assume the result is 0. Then we scan from both sides. If leftHeight < rightHeight, move right and find a value that is greater than leftHeight. Similarily, if leftHeight > rightHeight, move left and find a value that is greater than rightHeight. Additionally, keep tracking the max value.

    container with most water

  • 相关阅读:
    推荐一款idea 翻译插件 ECTranslation
    idea 执行maven 命令
    Future Clalback使用案例
    newCachedThreadPool使用案例
    线程池 原理学习笔记
    使用curator框架简单操作zookeeper 学习笔记
    mongo aggregate 用法记录
    ReentrantLock 学习笔记
    VUE:过渡&动画
    VUE:生命周期
  • 原文地址:https://www.cnblogs.com/kniught-ice/p/5159569.html
Copyright © 2011-2022 走看看