【LeetCode】11.Container With Most Water(Medium)解题报告
题目地址:https://leetcode.com/problems/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.
两层循环暴力解超时,题目不要求返回i和j,直接two pointer。要注意是矩形面积,最开始我当成梯形面积了。。。
Solution1(超时):
public class Solution {
public int maxArea(int[] height) {
int maxarea = 0;
for (int i = 0; i < height.length; i++)
for (int j = i + 1; j < height.length; j++)
maxarea = Math.max(maxarea, Math.min(height[i], height[j]) * (j - i));
return maxarea;
}
}
Solution2:
//time : O(n)
//space : O(1)
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int max = 0;
while(left<right){
max = Math.max(max,(right-left)*Math.min(height[left],height[right]));
if(height[left]<height[right]){
left++;
}else{
right--;
}
}
return max;
}
}
Date:2017年11月27日