Leetcode c语言-Container With Most Water

来源:互联网 发布:极客湾淘宝店 编辑:程序博客网 时间:2024/05/29 07:49

Title:

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 and n is at least 2.


这道题就是找出两条线,然后依据短板理论,求出两条线和x坐标轴包围的最大面积。


暴力解答就是利用嵌套循环,两个遍历字符串,遍历算出所有元素之间的面积大小,找到最大的即可解决。但会超时,贴出代码;

int maxArea(int* height, int heightSize) {        int i = 0  , j = heightSize -1 , max=0, temp = 0;          while(i<j) {                            if (height[i]<height[j]) {                  temp = (j - i) * height[i];                  i++;              } else {                  temp = (j - i) * height[j];                  j--;              }              if(temp>max) {                  max = temp;              }                        }          return max;  }

这种解答的时间复杂度为O(n^2),要降为O(n),才可以。



另一种解答就是两边同时向中间遍历,i=0,j=len-1。然后判断height(i)和height(j)的大小,如果前者小,计算出面积,然后i++,否则j--,也就是如果左边小,那么根据左边的大小计算出面积,然后往右移一位,重新比较。如果右边小,就根据右边算出面积,然后j--,也就是向左移一位,然后重新比较。直到i和j就差1即可,那么得到的最大的面积就是结果。

可能这种解答比较难理解,很多人会疑惑是不是存在很多种漏判的情况,比如右边左移,那么右边的数字就不能互相计算面积,右边的数字之间组成的面积就不会更大吗?

答案是不会的。

因为右边任意数字相组合,其较短的那一边永远会比之前计算过的边要小,右边任意数字中最长的那一边都是在之前计算中属于短的那一边,不然也不会右移了。

而右边数字之间的距离也永远不会比之前计算过的距离要短,因为右边数字之间的距离包含在之前计算的左边和右边之间的距离里面。


因此不会存在漏判的情况。贴出代码:

int maxArea(int* height, int heightSize) {        int i = 0  , j = heightSize -1 , max=0, temp = 0;          while(i<j) {                            if (height[i]<height[j]) {                  temp = (j - i) * height[i];                  i++;              } else {                  temp = (j - i) * height[j];                  j--;              }              if(temp>max) {                  max = temp;              }                        }          return max;  }



原创粉丝点击