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
}
}
func maxArea(height []int) int {
ans := 0
for i , j := 0, len(height) -1; i < j;{
ans = max(ans, min(height[i], height[j]) * (j - i))
if height[i] > height[j] {
j -= 1
} else {
i += 1
}
}
return ans
}
func min(a int, b int) int {
if a > b {
return b
} else {
return a
}
}
func max(a int, b int) int {
if a > b {
return a
} else {
return b
}
}
//使用单调栈处理
func maxArea(height []int) int {
var left = stack{}
var right = stack{}
res := 0
left.Push(0)
for i, v := range height {
if height[left.Top()] < v {
left.Push(i)
}
for (len(right.arr) != 0 && height[right.Top()] < height[i]) {
right.Pop()
}
right.Push(i)
}
for (len(right.arr) > 0){
r := right.Top()
right.Pop()
for i := 0; i < len(left.arr); i++{
l := left.arr[i]
if l > r { break }
curHeight := min(height[l], height[r])
res = max(res, curHeight * (r-l))
}
}
return res
}
type stack struct{
arr []int
}
func (s *stack) Push (val int){
s.arr = append(s.arr, val)
}
func (s *stack) Pop() {
var _ = s.arr[len(s.arr)-1]
s.arr = s.arr[0:len(s.arr)-1]
//return val
}
func (s *stack) Top() int{
return s.arr[len(s.arr)-1]
}
func max(a, b int) int {
if a > b {
return a
} else {
return b
}
}
func min(a, b int) int {
if a < b {
return a
} else {
return b
}
}