zoukankan      html  css  js  c++  java
  • leetcode刷题-11-盛最多水的容器

    问题描述

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

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

    示例

    输入: [1,8,6,2,5,4,8,3,7]
    输出: 49
    

    实现

    1 暴力破解

    暴力破解,时间复杂度$$O(n^{2})$$,超出官方指定时间限制,自己跑了一下大约是两秒半

    def max_area(height_list):
        height_num = len(height_list)
        max_area = 0
    	for i in range(height_num):
        current_val = height_list[i]
        for j in range(i+1, height_num):
            if current_val <= height_list[j]:
                area = current_val * (j-i)
            else:
                area = height_list[j] * (j-i)
            if max_area < area:
                max_area = area
    
    	return max_area`
    

    2 双指针法 头尾指针

    头尾指针,双向移动,每次移动较小值,时间复杂度$$O(n)$$

    def max_area_hash(height_list):
        list_length = len(height_list)
        rear_pointer = list_length - 1
        head_pointer = 0
    
        max_area = 0
    
        while(rear_pointer != head_pointer):
            if height_list[rear_pointer] >= height_list[head_pointer]:
                current_width = rear_pointer - head_pointer
                current_area = height_list[head_pointer] * current_width
                if max_area < current_area:
                    max_area = current_area
                head_pointer += 1
            else:
                current_width = rear_pointer - head_pointer
                current_area = height_list[rear_pointer] * current_width
                if max_area < current_area:
                    max_area = current_area
                rear_pointer -= 1
    
        return max_area'
    
  • 相关阅读:
    Shiro 学习笔记(Realm)
    Shiro 学习笔记(Authentication)
    Shiro 学习笔记(基本结构)
    POI 示例(导入,导出)
    SpringBoot 整合POI
    解决使用drf-haystack报错ImportError: cannot import name get_count
    python实现冒泡排序和插入排序
    九大排序算法总结(转)
    Djaong 数据库查询
    django session 和cookie的设置,获取和删除
  • 原文地址:https://www.cnblogs.com/liuheblog/p/12296405.html
Copyright © 2011-2022 走看看