本文主要是介绍leetcode-11. 盛最多水的容器(双指针),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
11. 盛最多水的容器
/*** @param {number[]} height* @return {number}*/
var maxArea = function (height) {// 时间复杂度 O(n)// 空间复杂度 O(1)let len = height.length;let left = 0,right = len - 1;let res = 0;while (left < right) {let area = Math.min(height[left], height[right]) * (right - left);res = Math.max(res, area);if (height[left] < height[right]) {left++;} else {right--;}}return res;
};console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]));
class Solution:def maxArea(self,height:List[int])->int:ans = 0left = 0right = len(height)-1while(left<right):area = (right-left)*min(height[left],height[right])ans = max(area,ans)if(height[left]<height[right]):left+=1else:right -=1return ans
reference
https://leetcode.cn/problems/container-with-most-water/
这篇关于leetcode-11. 盛最多水的容器(双指针)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!