zoukankan      html  css  js  c++  java
  • leetcode刷题笔记十一 盛最多水的容器 Scala版本

    leetcode刷题笔记十一 盛最多水的容器 Scala版本

    源地址:盛最多水的容器

    问题描述:

    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 and n is at least 2.

    The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

    Example:

    Input: [1,8,6,2,5,4,8,3,7]
    Output: 49
    

    简要思路分析:

    首先想到,可以通过暴力法计算任意两条线与X轴构成的面积,通过变量记录其中的最大值,并返回。但是这种复杂度较高。

    易知,最终面积是由连续的点构成的,我们可以视为最终面积是从起始点到终点构成的最初面积,不断舍去两侧的高度较低的线,使得面积更加集中。因此,我们可以通过双指针扫描法确定最大面积。

    代码补充:

    object Solution {
       def maxArea(height: Array[Int]): Int = {
          var maxArea = 0
          var leftArr = 0
          var rightArr = height.length-1
    
          while (leftArr < rightArr) {
            //println("-------------------------------------")
            //println("leftArr: "+ leftArr)
            //println("height(leftArr): "+height(leftArr))
            //println("rightArr:" + rightArr)
            //println("height(rightArr): "+height(rightArr))
            //println("maxArea: "+maxArea)
            var Area = (math.min(height(leftArr), height(rightArr)) * (rightArr-leftArr))
            //if (Area < maxArea) return maxArea
            //else {
              if (height(leftArr) < height(rightArr)) leftArr+=1
              else rightArr-=1
              if (Area> maxArea)maxArea = Area
            //}
    
          }
          return maxArea
        }
    }
    
  • 相关阅读:
    Haskell学习笔记--class/typeclass/show/read
    Haskell学习笔记--scanl/scanr
    Haskell学习笔记--foldl/flodr/高阶函数
    EasyUI 表单验证扩展(备忘录)
    基于FPGA的视频时序生成
    如何调用Altera FPGA的内嵌乘法器
    基于FPGA视频时序生成中的库文件
    基于FPGA的序列检测器10010
    NOIP2017游记
    【NOIP模拟赛】异象石
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/12693651.html
Copyright © 2011-2022 走看看