LeetCode11. 盛最多水的容器
一、题目描述
☆☆☆二、解法
【最优解】:双指针(对撞指针),时间复杂度O(n)
核心是 缩减搜索空间
class Solution { public int maxArea(int[] height) { /** * 方法1:暴力法,时间复杂度O(n^2) */ /*int res = 0; for (int i = 0; i < height.length - 1; i++) { for (int j = i + 1; j < height.length; j++) { int temp = (j - i) * Math.min(height[i], height[j]); res = Math.max(res, temp); } } return res;*/ /** * 方法2:对撞指针。 时间复杂度 O(n) 空间复杂度 O(1) * 思路:每次移动指针时,尽量保留比较高的边,让低边对应的指针向内移动,以获得有更高边的机会。 */ int res = 0; int l = 0, r = height.length - 1; while (l < r) { int temp = (r - l) * Math.min(height[l], height[r]); res = Math.max(res, temp); if (height[l] < height[r]) { l ++; }else { r --; } } return res; } }
重要参考题解:
O(n) 双指针解法:理解正确性、图解原理(C++/Java)