第三周:11. Container With Most Water
来源:互联网 发布:网络直播行业现状 编辑:程序博客网 时间:2024/05/21 10:11
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 and n is at least 2.
Subscribe to see which companies asked this question.
int maxArea(int* height, int heightSize) { int i,j;int result=0;int temp;for(i=0;i<heightSize;i++)for(j=i+1;j<heightSize;j++){if(height[i]<height[j])temp=height[i]*(j-i);else temp=height[j]*(j-i);if(result<temp)result=temp;}return result;}
显然这个方法会出现超时:
于是在网上看别人的解题思路:先拿最左边的线段和最右边的线段作为组合,计算出其乘积,然后,找两者中较为短的一方,慢慢向中间靠拢。
代码如下:
int maxArea(int* height, int heightSize) {int i=0,j=heightSize-1;int area;int result=0;while(i<j){if(height[i]<height[j]){area=height[i]*(j-i);i++;}else{area=height[j]*(j-i);j--;}if(result<area)result=area;}return result;}
0 0
- 第三周:11. Container With Most Water
- 11.Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11.Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 从Java内存模型理解synchronized、volatile和final关键字
- 蓝桥杯——舍罕王赏麦子
- 认识阶段:认知——固有属性和关联
- c++将string类型字符串转换成char *
- 5-9 抢红包 (25分)
- 第三周:11. Container With Most Water
- QSqlDatabase数据库
- iOS开发之UITableView , UICollectionView, UIScrollview,根据代理判断页面滚动方向。
- ORA-03113: end-of-file on communication channel
- 联合体(union)以及数据的存储
- 2753: [SCOI2012]滑雪与时间胶囊
- drp项目--采用dom4j对XML读取
- 算法:LeetCode240
- DNS服务器的学习和搭建