LeetCode之11---Container With Most Water
2016-04-08 18:00
357 查看
题目:
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.
题目大意:
给定一个数组,在数组中选取两个数字,数字的下标代表水桶的底面积,数字中较小的一个作为最终的桶高(短板定律),求这组数中最大的装水容量。按照题目的英文翻译过来看起来很奇怪。。。所以,转换成表达式吧,设i,j两个下标,求min(a[i], a[j]) * abs(i - j)的最大值。
思路1:
最先想到的是暴力求解法,一个双重循环,枚举所有情况,求得最大值然后返回。时间复杂度为O(n^2),不出意外的超时了。。。。
代码1:
class Solution { public: int maxArea(std::vector<int>& height) { int pos, max = 0; for (int i = 0; i < height.size(); ++i) { for (int j = i + 1; j < height.size(); ++j) { int tmp = (height[i] < height[j] ? height[i] : height[j]) * (j - i); if (max < tmp) { pos = i; max = tmp; } } } return max; } };
思路2:
第二个思路采用贪心的解决思路,先将距离置为最大(即:a.size() - 1 - 0),然后每次在缩小距离的同时让最小数不断增大,从而求得最优解。具体操作步骤如下:将i置为0,将j置为a.size()-1,然后每次判断a[i]<a[j]是否成立,如果成立则++i,如果不成立则--j(++i和--j的原因是不断增大所选择的较小值,如果选择此时的较小值进入下一次循环的话只会使下一次迭代的最小值比本次最小值小或等于本次最小值,这样则不符合最优解的条件)。
代码2:
class Solution { public: int maxArea(std::vector<int> &height) { int max = 0, i = 0, j = height.size() - 1, tmp = 0; while (i < j) { bool flag = height[i] < height[j] ? true : false; if (flag) { ++i; tmp = height[i] * (j - i); } else { --j; tmp = height[j] * (j - i); } if (tmp > max) { max = tmp; } } return max; } };
相关文章推荐
- Gradle project sync failed. Please fix your project and try again解决方案
- Logstash1.5 发邮件报警
- flask框架配置email问题汇总,包括163邮箱,qq邮箱,gmail等国内外邮箱
- 学习smail注入遇到的坑
- Service详解(六):进程间通信-AIDL
- MaraiDB社区
- 理解android.intent.action.MAIN 与 android.intent.category.LAUNCHER
- http://blog.csdn.net/chlele0105/article/details/9056951
- 11. Container With Most Water(头尾双指针)
- Mac电脑实用技巧(转自http://sspai.com/32769)
- Thumbnails 框架使用,图片常用操作
- 理论 E-learning课件AICC标准和SCORM标准
- lightoj 1252 - Maintaining Communities 树形DP
- 解决 Agent admitted failure to sign using the key 问题 with ssh
- [ActionScript 3.0] 安全沙箱的类型sandboxType,判断当前程序是AIR还是web程序
- 人工智能笔记
- 1090. Highest Price in Supply Chain (25)
- AIDL自我提醒,错误小注意
- 存储之磁盘阵列RAID
- DataInputStream和DataOutputStream使用方法细节探讨