Swift algorithm practice

Container With Most Water

2019-01-27  本文已影响8人  d1497e8e780a

Swift 4.2

class Solution {
  func maxArea(_ height: [Int]) -> Int {
    if height.count < 2 {
      return 0
    }
    var area = 0
    var leftIndex = 0
    var rightIndex = height.count - 1
    while (rightIndex - leftIndex) > 0 {
      let actualHeight = min(height[leftIndex],height[rightIndex])
      area = max(area, (rightIndex - leftIndex) * actualHeight)
      while height[leftIndex] <= actualHeight, leftIndex < rightIndex {
        leftIndex += 1
      }
      while height[rightIndex] <= actualHeight,leftIndex < rightIndex {
        rightIndex -= 1
      }
    }
    return area
  }

}
上一篇 下一篇

猜你喜欢

热点阅读