首页 > 其他 > 详细

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

时间:2020-04-13 20:40:15      阅读:63      评论:0      收藏:0      [点我收藏+]

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
    }
}

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

原文:https://www.cnblogs.com/ganshuoos/p/12693651.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!