经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
C++实现LeetCode(11.装最多水的容器)
来源:jb51  时间:2021/7/12 13:14:08  对本文有异议

[LeetCode] 11. Container With Most Water 装最多水的容器

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 nis at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

这道求装最多水的容器的题和那道 Trapping Rain Water 很类似,但又有些不同,那道题让求整个能收集雨水的量,这道只是让求最大的一个的装水量,而且还有一点不同的是,那道题容器边缘不能算在里面,而这道题却可以算,相比较来说还是这道题容易一些,这里需要定义i和j两个指针分别指向数组的左右两端,然后两个指针向中间搜索,每移动一次算一个值和结果比较取较大的,容器装水量的算法是找出左右两个边缘中较小的那个乘以两边缘的距离,代码如下:

C++ 解法一:

  1. class Solution {
  2. public:
  3. int maxArea(vector<int>& height) {
  4. int res = 0, i = 0, j = height.size() - 1;
  5. while (i < j) {
  6. res = max(res, min(height[i], height[j]) * (j - i));
  7. height[i] < height[j] ? ++i : --j;
  8. }
  9. return res;
  10. }
  11. };

Java 解法一:

  1. public class Solution {
  2. public int maxArea(int[] height) {
  3. int res = 0, i = 0, j = height.length - 1;
  4. while (i < j) {
  5. res = Math.max(res, Math.min(height[i], height[j]) * (j - i));
  6. if (height[i] < height[j]) ++i;
  7. else --j;
  8. }
  9. return res;
  10. }
  11. }

这里需要注意的是,由于 Java 中的三元运算符 A?B:C 必须须要有返回值,所以只能用 if..else.. 来替换,不知道 Java 对于三元运算符这么严格的限制的原因是什么。

下面这种方法是对上面的方法进行了小幅度的优化,对于相同的高度们直接移动i和j就行了,不再进行计算容量了,参见代码如下:

C++ 解法二:

  1. class Solution {
  2. public:
  3. int maxArea(vector<int>& height) {
  4. int res = 0, i = 0, j = height.size() - 1;
  5. while (i < j) {
  6. int h = min(height[i], height[j]);
  7. res = max(res, h * (j - i));
  8. while (i < j && h == height[i]) ++i;
  9. while (i < j && h == height[j]) --j;
  10. }
  11. return res;
  12. }
  13. };

Java 解法二:

  1. public class Solution {
  2. public int maxArea(int[] height) {
  3. int res = 0, i = 0, j = height.length - 1;
  4. while (i < j) {
  5. int h = Math.min(height[i], height[j]);
  6. res = Math.max(res, h * (j - i));
  7. while (i < j && h == height[i]) ++i;
  8. while (i < j && h == height[j]) --j;
  9. }
  10. return res;
  11. }
  12. }

到此这篇关于C++实现LeetCode(11.装最多水的容器)的文章就介绍到这了,更多相关C++实现装最多水的容器内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号