每天一题LeetCode[第八天]

来源:互联网 发布:淘宝查看浏览器插件 编辑:程序博客网 时间:2024/05/21 09:28

每天一题LeetCode[第八天]


Container with Most water

Description:

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.Subscribe to see which companies asked this question.

中文翻译:

 给n个非负数的整数,代表坐标轴的点(i,ai)。想象有n个垂直直线被绘画在坐标上,就像两个端点直线 在点(i,ai),(i,0)。找到两条直线,使得它们与x轴坐标组成一个容器,这个容器包含的水是最多的。 提醒:你不能倾斜这个容器并且n的最小值为2

解题思路:

  • 首选题目一开始又看错了。。。以后文章都要手动翻译成中文的,以提高英文阅读能力。

  • 在明白题意后,题意就是找最大面积矩形,大致思路如下:从两边向里面逼近,然后每一步如何前进呢?这要想清楚,两边那一边动呢? 想想下,如果两端对应的高度不一样,为了能找到最大边,是不是应该把最小一高度一端的距离 变化,才能保证每一步找的都是最大矩形的最大可能的下一个矩形。按着这个思路,撸码,借鉴top solution:


Java代码:

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

提高代码质量就是:积累精美的思路,优质的代码的过程。

0 0
原创粉丝点击