昨晚和师兄刷leetcode碰见一题
Container With Most Water
题目大概意思是给出一个数组,然后把它用x-y坐标轴这样表示出来,连接任意两个高度,使构成的矩形面积最大?
有两种方法:1
第一个和第二个,第三个,第四个。。。求出面积。
第二个和第三个,第四个,第五个。。。求出面积。
max求最大,
继续一直到第n个,这样明显复杂度升高了。太暴力。

class Solution {
    public int maxArea(int[] height) {
       int max=0;
        for(int i=0;i<height.length;i++){
            for(int j=i;j<height.length;j++){
                max=Math.max(max,Math.min(height[i],height[j]) *(j-i));
            }
        }
        return max;
}
}

我么来看一下
Container With Most Water
方法2.
令出两个游标left,right,如果left对应的长度小于right的长度,则left++,反之right–;

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

Container With Most Water

相关文章:

  • 2021-09-04
  • 2021-04-30
  • 2021-11-23
猜你喜欢
  • 2021-09-29
  • 2022-03-10
相关资源
相似解决方案