zoukankan      html  css  js  c++  java
  • Container with most water

    1. Question

     给n个非负整数,在二维坐标系中,将(i,ai)与(i,0)连线,得到n条线。从n条线中找两条,与x轴构成一个非密封容器(容器不能倾斜),使得该容器盛水量最多。

    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.

    2. Solution

    2.1 O(n2)

    遍历所有的线组合,计算得到最大的。

    2.2 O(n)

    采用双指针。实际面积是min(ai, aj)*(j-i)

    • pi = 0;
    • pj = len-1;
    • 计算点ai和点aj所在的线构成的面积,并与max_area比较。
      • 如果ai <= aj, i++ (此时,ai是实际面积计算中的高,而此时的宽已是最大,从而以ai为高的最大面积已经计算得到,无需再考虑以ai为高的区域。此外,在一次次指针行走后,总能保证当前的某个指针所指的点高度比排除掉的任意点要高,从而即使后来遇到比之前排除掉的更低的点,也依然可以得到以该更低点为高的最大面积,因此无需再考虑以ai为梯形中的较高边的情况。总而言之,此时ai所在线无需再考虑)
      • 如果aj > ai, j--
    import java.util.Map.Entry;
    
    public class Solution {
        public int maxArea( int[] height ){
            int left = 0;
            int right = height.length - 1;
            int maxArea = 0;
            while( left < right ){
                int nowH;
                if( height[left] < height[right] )
                    nowH = height[left++];
                else
                    nowH = height[right--];
                maxArea = Math.max( maxArea, (right-left+1) * nowH );
            }
            return maxArea;
        }
    }
    View Code

            

  • 相关阅读:
    PVID和VID与交换机端口
    IO密集型和CPU密集型区别?
    Redis回收进程是如何工作的
    索引的工作原理及其种类
    drop,delete与truncate的区别
    你用过的爬虫框架或者模块有哪些?优缺点?
    列举您使用过的Python网络爬虫所用到的网络数据包
    对cookies与session的了解?他们能单独用吗
    有用过Django REST framework吗
    Django中哪里用到了线程?哪里用到了协程?哪里用到了进程
  • 原文地址:https://www.cnblogs.com/hf-cherish/p/4596365.html
Copyright © 2011-2022 走看看