zoukankan      html  css  js  c++  java
  • 盛最多水的容器(Python and C++解法)

    题目:

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

    说明:你不能倾斜容器,且 n 的值至少为 2。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/container-with-most-water

    思路:

      最优的做法是双指针,但需要知道一个前提(原因需要数学证明): 对应的数字较小的那个指针需要往另一个指针的方向移动一个位置,且这个指针不可能再作为最大容器的边界了。

    Python解法:

     1 class Solution:
     2     def maxArea(self, height: List[int]) -> int:
     3         left = 0  # 左指针
     4         right = len(height) - 1  # 右指针 
     5         res = []
     6         while left < right:
     7             temp = min(height[left], height[right]) * (right - left)
     8             res.append(temp)
     9             if height[left] <= height[right]:
    10                 left += 1
    11             else:
    12                 right -= 1
    13         return max(res)

    C++解法:

     1 class Solution {
     2 public:
     3     int maxArea(vector<int>& height) {
     4         int left = 0, right = height.size()-1;  // 左右指针
     5         vector<int> tempRes;
     6         while(left < right) {
     7             int temp = min(height[left], height[right]) * (right - left);  // 计算面积
     8             tempRes.push_back(temp);
     9             if(height[left] <= height[right])
    10                 left++;
    11             else
    12                 right--;
    13         }
    14         return *max_element(tempRes.begin(), tempRes.end());  // 找vector最大值并返回
    15     }
    16 };
  • 相关阅读:
    java怎么导入一个项目到eclipse
    JDK安装与环境变量配置(链接by网络)
    配置安装ecplise跑项目
    电脑缺少**.dll文件
    Microsoft-Office-Professional-Plus-2007
    win7如何恢复以前的ie版本
    maven安装及maven项目导入流程(网络链接)
    LoadRunner录制Web协议的脚本 (by网络)
    spring中jdbc.properties用法
    linux 安装 mysql
  • 原文地址:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13519541.html
Copyright © 2011-2022 走看看