《leetCode》:Container With Most Water
2015-11-16 21:55
323 查看
题目
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.
题目大意:使容器装更多的水
思路一:暴力搜索法
寻找体积最大,容器的体积由两个高度中较低的高度和圆底的半径决定:area=min(height[i],height[j])*(j-i)
实现代码如下:
int min(int a,int b){ return a<=b?a:b; } int maxArea(int* height, int heightSize) { if(height==NULL||heightSize<1){ return 0; } int max=0; for(int i=0;i<heightSize;i++){ for(int j=i+1;j<heightSize;j++){ int area=min(height[i],height[j])*(j-i); if(area>max){ max=area; } } } return max; }
时间复杂度为O(n^2),报超时错误。因此需要寻找更好的方法来实现。
思路二
思路:一个容器装水只能由两个高度中最低的高度作为容器的高度。
如果我们从两个数相隔最远的长度(即第一个和最后一个元素),那么我们将得到一个最大宽度的矩形。
现在,我们可以移动高度较小的那个高度(即较少宽度,但是高度可能增加,这样总面积可能也会增加),来获取最大的总面积
这种思路的时间复杂度为O(n)
int min(int a,int b){ return a<=b?a:b; } int maxArea(int* height, int heightSize) { if(height==NULL||heightSize<1){ return 0; } int max=0; int begin=0; int end=heightSize-1; while(begin<end){ int area=min(height[begin],height[end])*(end-begin); if(area>max){ max=area; } if(height[begin]>height[end]){ end--; } else {//if(height[begin]<=height[end]) begin++; } } return max; }
AC结果如下:
相关文章推荐
- You can fail at what you don't want, so you might as well take a chance on doing what you love.
- 【论文笔记】The Impact of Imbalanced Training Data for CNN
- 关于《游戏编程中的人工智能》的源代码的小错误
- IO(一):传统IO(基于字符,字节,Socket) 与BIO,NIO,AIO 介绍
- 使用Email发送功能
- 【FZU】2208 cleaning again【模数质因数以3为众数的三进制NTT】
- poj 3250 Bad Hair Day(单调栈)
- Commons-Email 简单教程
- 软件磁盘阵列(Software RAID)
- windows服务器配置硬盘镜像阵列-软RAID
- 巧妙地利用STL map set pair 贪心+排序 Codeforces Round #331 (Div. 2)C. Wilbur and Points
- POJ 3250 Bad Hair Day(单调栈stack)
- 找不到dubbo:annotaion错误
- hihoCoder 1251 Today Is a Rainy Day(暴力)
- [论文笔记5]A Discriminatively Trained, Multiscale, Deformable Part Model
- raid 0,1,10,5特性
- 使用AIDL实现进程间的通信
- 【poj3831】Open-air shopping malls
- ArtifactTransferException: Failure to transfer com.sun.xml.bind:jaxb-xjc:jar:2.0.1 from http://192.1
- 转自 http://aikilis.tk/:0x3f3f3f3f作无穷大的精妙