【LeetCode】11. 盛最多水的容器

╰半夏微凉° 2022-05-05 10:58 258阅读 0赞

题目链接:https://leetcode-cn.com/problems/container-with-most-water/description/

题目描述

给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器,且 n 的值至少为 2。
在这里插入图片描述
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例

输入: [1,8,6,2,5,4,8,3,7]
输出: 49

解决方法

有两种方法:一是暴力枚举,二是用双指针

  1. // class Solution {
  2. // public:
  3. // int maxArea(vector<int>& height) {
  4. // //方法1:暴力枚举
  5. // if (height.size()==2) return min(height[0],height[1]);
  6. // int result=INT_MIN;
  7. // for (int i=0;i<height.size();i++)
  8. // for (int j=height.size()-1;j>=0;j--){
  9. // if (i>=j) break;
  10. // result=max(result,(j-i)*min(height[i],height[j]))
  11. // }
  12. // return result;
  13. // }
  14. // };
  15. class Solution {
  16. public:
  17. int maxArea(vector<int>& height) {
  18. //方法2:双指针
  19. if (height.size()==2) return min(height[0],height[1]);
  20. int result=INT_MIN;
  21. int left=0,right=height.size()-1;
  22. while(left<right){
  23. result=max(result,(right-left)*min(height[left],height[right]));
  24. if (height[left]<height[right]) left++;
  25. else right--;
  26. }
  27. return result;
  28. }
  29. };

发表评论

表情:
评论列表 (有 0 条评论,258人围观)

还没有评论,来说两句吧...

相关阅读