面试题:[Container the most water]容器中最大水容量

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

题是leetcode上看到的,是说给你一个数组,非负整形的,这些数值都能在坐标系中以点的形式表示出来。比如说:

[1,3,1,8,3],这里面数组里值的位置作为横坐标,值代表纵坐标, 形成的点就是(1.1) (2,3) (3,1) (4,8) (5,3), 每个点和x轴连线,任意两根线和x轴就形成了一个容器,求容器的最大水容量。容器不能倾斜

naive的办法就是2个循环嵌套,把任意两个值都试一遍,时间是O(n^2),显然时间太长

其实linear的时间就可以完成,代码如下:

public static int maxArea(int[] height){

		

          int maxH=0;
		int equation=0;
		
		int i=0,j=height.length-1;
            while(i!=j){
          		int edge=Math.min(height[i],height[j]);
          		equation=(edge)*(j-i);
          		maxH=Math.max(maxH,equation);
          		if(height[i]<height[j]) i++;
          		else j--;
            }

        
        return maxH;

	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值