• Container With Most Water


    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 end points 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 containsthe most water.

    Note:You may not slant the container.

     

    思路:解题的前提是要理解题目,该题的题目是:给定n个非负整数,每一个整数代表了一个坐标(i, ai),坐标(i, 0)和(i, ai)形成一条竖线。要求找到两条竖线,他们和x轴共同组成了一个容器,要求该容器盛的水最多。而且,该容器不能倾斜。


    需要注意的是:两条竖线和x轴组成的容器,与两条竖线之间的点没有关系,决定该容器面积(盛水量)的元素只有这两条线的位置,也就是(i, xi)和(j, xj)两个坐标。而且该容器不能倾斜,意味着,该容器的盛水量,取决于较短的那条竖线。


    理解了题意之后,在思考如何解题。


    普通的解法是:分别轮训起点和终点,求得每种情况的面积,让后取最大值,这样的时间复杂度是O(n^2)。


    更快的方式是O(n)的,面积取决于x轴的长度,以及高度,即两个坐标中较小整数的值。一开始就把x轴最长的情况作为基准,考虑如何寻找更大面积的情况。代码如下:

     

    #define min(x, y)  (((x)<(y))?(x):(y))
    
    int maxArea(int* height, int heightSize) 
    {
    	int i, j;
    	int res = 0;
    	int area = 0;
    	
    	i = 0; 
    	j = heightSize-1;
    	
    	while(i < j)
    	{
    	    area = min(height[i], height[j])*(j-i);
    	    if(res < area)  res = area;
    	    
    	    if(height[i] < height[j])   i++;
    	    else    j--;
    	}
    
    	return res;
    }
    

      


     

  • 相关阅读:
    POJ——T2186 Popular Cows || 洛谷——P2341 [HAOI2006]受欢迎的牛
    Tarjan缩点【模板】
    shell(1):网络配置、BATH环境和通配符
    STL
    J
    H
    G
    模板整理(二)
    B
    0-1背包问题
  • 原文地址:https://www.cnblogs.com/gqtcgq/p/7247153.html
Copyright © 2020-2023  润新知