• 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 n is at least 2.

    思路:

    暴力计算所有的ai,aj组合,计算过程利用如下性质:记录当前取得max_area时的max_start和max_end,固定ai,从右遍历aj时,aj必须大于max_end才有可能超过当前max_area。外层循环从左开始遍历ai,只有ai大于max_start才有可能超过max_area。

    代码:

     1 class Solution {
     2 public:
     3     int maxArea(vector<int>& height) {
     4         int max_area = 0;
     5         int max_end = 0;
     6         int max_start = 0;
     7         for(int i = 0;i < height.size();i++)
     8         {
     9             if(height[i] > max_start)
    10             {
    11                 for(int j = height.size() - 1;j > i;j--)
    12                 {
    13                     if(height[j] >= max_end)
    14                     {
    15                         int temp_area = (j - i) * min(height[i],height[j]);
    16                         if(temp_area > max_area)
    17                         {
    18                             max_start = height[i];
    19                             max_end = height[j];
    20                             max_area = temp_area;
    21                         }
    22                     }
    23                 }
    24             }
    25         }
    26         return max_area;
    27     }
    28 };

    这个解法比较low,时间复杂度应该还是o(n2),leetcode上o(n)的解法可参见:

    https://leetcode.com/problems/container-with-most-water/solution/

  • 相关阅读:
    nodejs-supervisor
    javascript数组操作(创建、元素删除、数组的拷贝)
    mysql索引优化-order/group
    php-kafka
    大流量高并发解决方案
    MySQL数据类型和常用字段属性总结
    php一致性hash算法
    面试中的排序算法总结
    PHP的运行机制与原理(底层)
    Mysql中的锁机制
  • 原文地址:https://www.cnblogs.com/tracy520/p/8320718.html
Copyright © 2020-2023  润新知