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.

 
二、题目大意

 

给定一个代表高度的整数列表,返回其中任意两个高度与两者水平距离组成的最大矩阵面积。


三、思路分析

 

别人的思路:

设定两个头尾游标i和j,i-j的绝对值就是宽度,i和j位置的元素就是高度,通过不断寻找最高高度,来求得最大矩阵面积。作者注释解释很清楚。

 

本人的思路:

遍历列表nums的元素,当nums[i]>nums[len(nums)-1] ,取nums[i]计算面积,否则取后者计算面积。求取遍历过程中的最大值。

 

四、具体代码

 

作者的代码:

class Solution:
    def maxArea(self, height):
        i = 0 # i points to the beginning
        j = len(height) - 1 # j points to the end
        max_area = 0
        while i < j: # i and j will get closer to eachother but never pass, ensuring every element is only visited once
            width = abs(i-j) # the distance between i and j, set before i or j is reassigned
            if height[i] < height[j]: # the lower wall dictates vertical distance bc gravity
                h = height[i]
                i += 1 # if the i wall is lower, move forward to try to find a taller wall
            else:
                h=height[j]
                j-=1# if the j wall is lower, move backwards to try to find a taller wall
            max_area = max(max_area, h * width)
        return max_area

本人的代码:

class Solution:
    def maxArea(self, height: List[int]) -> int:
        length=len(height)-1
        trail=height[length]
        max1=-99999999
        for i in range(length):
            if height[i]>=trail:
                s=trail*(length-i)
            else:
                s=height[i]*(length-i)
            max1=max(s,max1)
        return max1

 

 

五、两者差别

1.本人只考虑水平距离的变化,把最后一个高度值作为默认取值,但是水平距离和高度都会发生改变,所以写出来代码通不过。

底边的变化是通过:下标差的绝对值 (列表的下标)

高度的变化是通过:nums[j]的变化(列表的值)

2.作者通过设置头尾游标来动态的改变是个不错的选择。作者通过表示出宽和高来计算面积,中间加上了对于高度的讨论,这个思路看起来很简单,但是本人做题的时候是不知怎么下手,这也看到了整体把握的重要。本人思考中心放到了如何直接计算最大值,而不是通过表示出面积,来分析最大值,是最大的误区,以至于搞不清。

 

六、知识点总结

1.整体思维的把握,对于问题要认清到底什么是本质。

2.用纸记录讨论情况,有些讨论太多,单独想想不清。

3.对于下标的变换,可以用“游标遍历的思维”。

 

七、.来源


题目连接:https://leetcode.com/problems/container-with-most-water/

作者原文解答:https://leetcode.com/problems/container-with-most-water/discuss/156622/Python-2.7-O(N)

 
座右铭:站在别人的思想上,看见自己的不足,传播错误的经验,愿君不重蹈覆辙。

 

由于受限于本人经验,难免不足,如有建议,欢迎留言交流。

 

说明:作者代码能通过测试,本人亲测。如果喜欢,请点赞,您的鼓励是本人前进的最好动力。


--------------------- 
作者:路漫漫,远修兮 
来源:CSDN 
原文:https://blog.csdn.net/qq_41827968/article/details/88756403 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值