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 }
  • 相关阅读:
    filp_open/filp_close/vfs_read/vfs_write
    memcpy一种实现方法
    memset函数的实现&printf函数几种输出格式的输出结果
    break退出循环分析
    定义指针变量作为返回值函数执行时报 段错误(核心已转储)
    node实现防盗链
    js实现输入密码之延迟星号和点击按钮显示或隐藏
    rem适配
    使用字蛛教程以及遇到的bug
    es6学习笔记-proxy对象
  • 原文地址:https://www.cnblogs.com/zhaolizhen/p/Containerwater.html
Copyright © 2011-2022 走看看