zoukankan      html  css  js  c++  java
  • leetcode:Container With Most Water(容器装更多的水)

    Question:

    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.

    Note: You may not slant the container.

    上边比较简单的表述转化为数学为:给定一个数组height[n];i,j都是数组的下标,找到(j-i)*min( heigth[i],height[j] )最大的数。

    算法思想:① 这个题没有想象中的复杂,其实就是TwoSum的思想,设计两个指针i和j, i从左向右扫描,j 从右向左扫描,设计一变量max记录最大值。

         ② 思想就是 height[i]和heigth[j] 谁小谁移动,假如height[i]<height[j], 在两个选较小的,所以拿(j-i)*height[i]和max比较,如果大于max,max被重新赋值,因为height[i]小,所以i++,向前推进。

         ③ 对于右边的扫描是同样的道理,最后返回max。

    代码设计:

     1 class Solution {
     2 public int maxArea(int[] height) {
     3         int i=0;//从左往右扫描
     4         int j=height.length-1;//从右向左扫描
     5         int max=0;//用来记录最大值
     6         while(i<j){
     7             if(height[i]<height[j]){//如果左边的数小于右边的数
     8                 if((j-i)*height[i]>max)  
     9                     max=(j-i)*height[i];
    10                 i++;
    11             }
    12             else{//如果右边的数小于左边的数
    13                 if((j-i)*height[j]>max)
    14                     max=(j-i)*height[j];
    15                 j--;
    16             }
    17         }
    18         return max;
    19     }
    20 }
  • 相关阅读:
    VS2017常用快捷键
    浅谈JS之setTimeout与setInterval
    你真的了解foreach吗?
    IEnumerable和IEnumerator详解
    Cesium坐标系及坐标转换详解
    NPM常用指令
    ASP.NET Web API 2系列(三):查看WebAPI接口的详细说明及测试接口
    【nginx】安装nginx
    【redis】本地连接服务器的redis教程
    Mysql5.7及以上版本 ONLY_FULL_GROUP_BY报错的解决方法
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/Containerwater.html
Copyright © 2011-2022 走看看