标签:mos code min water for containe inter contain color
首先想到的肯定是暴力解法,O(n^2)。
class Solution { public int maxArea(int[] height) { // int[][] dp = new int[height.length][height.length]; int max=0; for(int i=0;i<height.length-1;i++) { for(int j=i+1;j<height.length;j++) { // dp[i][j]=(j-i)*Math.min(height[i], height[j]); max = Math.max(max, (j-i)*Math.min(height[i], height[j])); } } return max; } }
421ms,8.51%,肯定不行,思考更优解法。
自己想到了two pointer,但是没有彻底想明白,看了solution后明白了。
class Solution { public int maxArea(int[] height) { int max=0,l=0,r=height.length-1; while(l<r) { max = Math.max(max, (r-l)*Math.min(height[l], height[r])); if(height[l]>height[r]) r--; else l++; } return max; } }
6ms,66.7%,O(n)。和3ms答案基本一个思路了,可以了。
Leetcode11 Container With Most Water
标签:mos code min water for containe inter contain color
原文地址:https://www.cnblogs.com/chason95/p/9984592.html