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 };
  • 相关阅读:
    数据库水平切分的实现原理解析---分库,分表,主从,集群,负载均衡器
    现代 PHP 新特性系列(六) —— Zend Opcache
    Apache配置参数详解
    Git的常用命令
    PHP如何防止XSS攻击
    CSRF的防御实例(PHP)
    Web安全之CSRF攻击
    PHP五种常见的设计模式
    PHP四种基础算法详解
    php遍历文件的5种方式
  • 原文地址:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13519541.html
Copyright © 2011-2022 走看看