当前位置:网站首页>Container containing the most water

Container containing the most water

2022-06-10 18:04:00 Elite cadre flaw light

original edition :

        

Personal translation :

Given an array of integers , Enumerate , The index is X Axis , Values are Y Axis , Find out the maximum area of two of them .

Start with your own ideas and operations .

Design a two-layer loop , Set up a maximum area s1=0, Each number is traversed backwards from itself , Find the maximum area replacement s1, The code is as follows :

class Solution:
    def maxArea(self, height: List[int]) -> int:
        carry=0
        for i in range(len(height)):
            for j in range(i,len(height)):
                cantake=(j-i)*min(height[i],height[j])       
                carry=max(cantake,carry)
        return carry

result : Failure , Code timeout .

        This double-layer loop is equivalent to traversing the list once for each number , Too much work .

right key :

class Solution:
    def maxArea(self, height: List[int]) -> int:
        l, r = 0, len(height) - 1
        ans = 0
        while l < r:
            area = min(height[l], height[r]) * (r - l)
            ans = max(ans, area)
            if height[l] <= height[r]:
                l += 1
            else:
                r -= 1
        return ans

Use double pointer , Point to both ends of the list , Move to the middle . Use while You can avoid setting boundary values , At the same time, it is obviously more concise than double loop operation .

原网站

版权声明
本文为[Elite cadre flaw light]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101715281342.html