美文网首页
1.LeetCode刷题For Swift·11. Contai

1.LeetCode刷题For Swift·11. Contai

作者: 富城 | 来源:发表于2020-12-23 09:38 被阅读0次

    1、原题

    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 the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.

    Notice that you may not slant the container.

    最大容器.jpg

    Example 1:

    Input: height = [1,8,6,2,5,4,8,3,7]
    Output: 49
    Explanation: 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 2:

    Input: height = [1,1]
    Output: 1
    

    Example 3:

    Input: height = [4,3,2,1,4]
    Output: 16
    

    Example 4:

    Input: height = [1,2,1]
    Output: 2
    

    2、思路

    3、代码

    class Solution {
        func maxArea(_ height: [Int]) -> Int {
            // 定义最大面积
            var max = 0
            // 使用首尾逼近的方法
            var i = 0
            var j = height.count - 1
            // 定义需要的最小高度
            var minHeight = 0
            // 循环逼近
            while i < j {
                // 得出每次的最小高度
                if height[i] < height[j] {
                    minHeight = height[i]
                    // 左边的高度最小,就将左边的边界右移一位
                    i+=1 
                } else {
                    minHeight = height[j]
                    // 右边的高度最小,就将右边的边界左移一位
                    j-=1
                }
                // 计算面积,因为最小的高度才是决定面积的
                let area = (j - i + 1) * minHeight
                // 比较得出最大面积
                max = max > area ? max : area
            }
            return max
        }
    }
    

    相关文章

      网友评论

          本文标题:1.LeetCode刷题For Swift·11. Contai

          本文链接:https://www.haomeiwen.com/subject/gvhynktx.html