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.
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轴构成的最大区域,一般来说最常见的想法就是遍历所有可能性然后找到最大值,时间复杂度O(n2),代码如下:
class Solution {
public int maxArea(int[] height) {
int i, j;
int max = 0, temp = 0;;
for(i = 0; i < height.length; i++){
for(j = 0; j < i; j++){
int l = i - j;
int h = height[i] > height[j]? height[j]: height[i];
temp = h * l;
if(temp > max)
max = temp;
}
}
return max;
}
}
非常耗时,215ms……
然后题目有给出一个solution说可以先取x轴上距离最长的两条垂直线段求max area,然后每次移动较短的那根垂直线来起到更新数据的效果,其实也比较好理解,因为当只有移动了较短边才有可能得到比初始情况下更大的范围(在x已经减少的情况下,需要增加height才有可能得到更大的max area),这样时间复杂度只是O(n),耗时5ms
class Solution {
public int maxArea(int[] height) {
int i = 0, j = height.length - 1;
int n = j - i;
int max = 0, temp = 0;
while(true){
int l = j - i;
int h1 = height[i];
int h2 = height[j];
int h = h1 > h2? h2: h1;
temp = h * l;
if(temp > max)
max = temp;
if(h1 > h2)
j--;
else
i++;
n = j - i;
if(n < 1)
break;
}
return max;
}
}
其他
终于放假了有点小开心
考试周真的会死人的
代码素养还是要加强……很多想法不看solution就想不到这样不行……
希望可以在寒假好好的刷leetcode