Container With Most Water (最大盛水量)leetcode11

约定不等于承诺〃 2022-05-24 02:57 248阅读 0赞

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.

给定一个数组每个数代表一块木板的高度横坐标x的宽度代表木桶的宽度,求最大容积(木桶的高只能为两块木板的最低的那一个)

code1:暴力破解,所有结果求出来取最大值(超时)

  1. public int maxArea(int[] height) {
  2. /*int max=Integer.MIN_VALUE;
  3. for(int i=0;i<height.length;i++){
  4. for(int j=i+1;j<height.length;j++){
  5. int h=height[i]>height[j]?height[j]:height[i];
  6. if(h*(j-i)>max)
  7. max=h*(j-i);
  8. }
  9. }
  10. return max;
  11. }

code2:假设第1块木板和最后一块组成的容积最大,如果还有更大的,那么小的木板往中心移,知道左边的木板位置等于右边模板的位置

20180518235931436

code:

  1. public int maxArea(int[] height) {
  2. int max=Integer.MIN_VALUE;
  3. for(int i=0,j=height.length-1;i<j;){
  4. if(height[i]>height[j]){
  5. max=Math.max(max,height[j]*(j-i));
  6. j--;
  7. }else{
  8. max=Math.max(max,height[i]*(j-i));
  9. i++;
  10. }
  11. }
  12. return max;
  13. }

发表评论

表情:
评论列表 (有 0 条评论,248人围观)

还没有评论,来说两句吧...

相关阅读