zoukankan      html  css  js  c++  java
  • 【LeetCode】011 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.

    题解:

      暴力解即可,注意这个面积是长方形的,我刚开始犯傻给写成梯形了。。。两个思路:两个for循环遍历,结果就是TLE了。另一个就是头尾指针遍历法,时间复杂度降为O(n).以后遇到这种需要遍历的,要先想到头尾指针法,而不是两个for循环(其实也是双指针,只是位置不一样)。同时,与之前遇到的数组问题一样,小幅度的优化就是在大循环内就跳过重复项

    Solution 1 (TLE)

    class Solution {
    public:
        int maxArea(vector<int>& height) {
            int area = 0, n = height.size();
            for(int i=0; i<n-1; i++) {
                for(int j=i+1; j<n; j++) {
                    int new_area = (j-i)*min(height[i], height[j]);
                    if(height[i]==0 || height[j]==0) new_area = 0;
                    area = max(area, new_area);
                }
            }    
            return area;
        }
    };

      

    Solution 2

    class Solution {
    public:
        int maxArea(vector<int>& height) {
            int area = 0, i = 0, j = height.size() - 1;
            while (i < j) {
                area = max(area, min(height[i], height[j]) * (j - i));
                height[i] < height[j] ? ++i : --j;
            }
            return area;
        }
    };

    Solution 3

    class Solution {
    public:
        int maxArea(vector<int>& height) {
            int area = 0;
            int i = 0, j = height.size() - 1;
            while (i < j) {
                 int h = min(height[i], height[j]);
                area = max(area, (j - i) * h);
                while (height[i] <= h && i < j) i++;
                while (height[j] <= h && i < j) j--;
            }
            return area;
        }
    }; 
  • 相关阅读:
    利用GetInvalidFileNameChars()得到有效的文件名
    C# 下载远程http文件到本地
    CLR无法从COM 上下文*****转换为COM上下文*****,这种状态已持续60秒。
    Wpf UserControl使用 KeyBinding,失效问题
    C# windows服务知识集锦
    制作Windows服务和安装程序(C#版)
    C语言内存管理
    Python初学注意问题
    msp430学习笔记-USART
    msp430学习笔记-ADC12
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6718649.html
Copyright © 2011-2022 走看看