zoukankan      html  css  js  c++  java
  • LeetCode Container With Most Water

    class Solution{
        public:
            int maxArea(vector<int>& height) {  
            int len = height.size(), low = 0, high = len -1 ;  
            int maxArea = 0;  
            while (low < high) {  
                maxArea = max(maxArea, (high - low) * min(height[low], height[high]));  
                if (height[low] < height[high]) {  
                    low++;  
                } else {  
                    high--;  
                }  
            }  
            return maxArea;  
        }
    };

    应该算是贪婪算法吧,直接从disscus里抄了,自己只能想出一个nlogn的,对贪婪没什么感觉,想不到

    第二轮:

    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.

    以前leetcode还没有标flag,现在可以看到这题标了two pointer就是2sum这种类似,首先最大的可能是由两端的作为容器壁,然后慢慢往内收缩尝试,收缩过程中放弃比较低的容器壁。反正这次又没想出来还看错题目,智商拙计啊:

     1 // 9:44
     2 class Solution {
     3 public:
     4     int maxArea(vector<int>& height) {
     5         int len = height.size();
     6         int lo = 0, hi = len - 1;
     7         int maxarea = 0;
     8         while (lo < hi) {
     9             maxarea = max(maxarea, min(height[lo], height[hi]) * (hi - lo));
    10             if (height[lo] < height[hi]) {
    11                 lo++;
    12             } else {
    13                 hi--;
    14             }
    15         }
    16         
    17         return maxarea;
    18     }
    19 };
  • 相关阅读:
    linux samba 配置
    实例解读 linux 网卡驱动
    Linux操作系统的安全管理设置
    找回Linux/Unix下各系统的密码
    CF441E Valera and Number
    CF1175F The Number of Subpermutations 题解
    CF1553 比赛记录
    P5618 [SDOI2015]道路修建 题解
    CF 1530 比赛记录
    AT2063 [AGC005E] Sugigma: The Showdown 题解
  • 原文地址:https://www.cnblogs.com/lailailai/p/3715508.html
Copyright © 2011-2022 走看看