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 }
  • 相关阅读:
    Browsersync 浏览器自动刷新
    react学习历程问题记载(二)
    react学习历程问题记载(一)
    LessJs笔记
    toFixed的使用
    react+ts封装AntdUI的日期选择框之月份选择器DatePicker.month
    elementUI实现日期框选中项文本高亮
    react+lib-flexible适配浏览器宽度配置
    vue+lib-flexible实现大小屏幕,超大屏幕的适配展示。
    div+伪元素实现太极图
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/Containerwater.html
Copyright © 2011-2022 走看看