• 蜗牛慢慢爬 LeetCode 11. Container With Most Water [Difficulty: Medium]


    题目

    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.

    翻译

    给定n个非负整数a1,a2,...,an,其中每个表示坐标(i,ai)处的点。绘制n条垂直线,使得线i的两个端点处于(i,ai)和(i,0)。找到两条线,它们与x轴一起形成容器,使得容器含有最多的水。

    Hints

    Related Topics: Array, Two Points
    容器是有木桶效应的 也就是说短的垂直线决定了整个容器的高 所要求的是 max(短边*坐标差)
    找到一些最大值的一般想法是通过可能发生最大值的所有情况,并继续更新最大值。为了提高扫描效率,要找到一种智能的扫描方式来切断无用的情况,同时100%保证通过其他情况可以达到最大值
    这儿可以通过设置左右两端的初始指针,向中间扫描,每次只移动较小值的指针 每一次移动都更新最大值

    代码

    Java

    class Solution {
        public int maxArea(int[] height) {
            int left,right;
            left = 0;right = height.length-1;
            int maxArea = 0;
            while(left<right){
                maxArea = Math.max(maxArea, (right-left)*(Math.min(height[left],height[right])));
                if(height[left]<height[right])
                    left++;
                else
                    right--;
            }
            return maxArea;
        }
    }
    

    Python

    class Solution(object):
        def maxArea(self, height):
            l = 0; r = len(height)-1;
            maxArea = 0
            while l<r:
                maxArea = max(maxArea, (r-l)*min(height[l],height[r]))
                if height[l]<height[r]:
                    l += 1
                else:
                    r -= 1
            return maxArea
                    
    
  • 相关阅读:
    Jquery基于ActiveX的批量上传
    枚举类型在as3中的实现
    delphi操作word基类,插入表格,分页符,日期,页码,替换,图片
    消除文本锯齿
    As3显示对象scrollRect滚动问题
    Bitmap序列化
    加载图片的方法
    球体旋转坐标推导
    AS3基于TextField实现图文并排更新于2015.08.05
    Flash与外部程序之间的通信
  • 原文地址:https://www.cnblogs.com/cookielbsc/p/7487267.html
Copyright © 2020-2023  润新知