Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:11. 盛最多水的容器,for循环双指针,JavaScript,详细注释 #137

Open
chencl1986 opened this issue Aug 22, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/container-with-most-water/

解题思路:

可以参考官方题解双指针法正确性证明

  1. 使用两个指针分别指向数组的头尾,对比两个指针对应的值,将值小的指针向内移动。
  2. 移动的对比每个位置的面积,取最大值并缓存。
  3. 两个指针不断移动,最后必然相遇,此时已完成对数组的遍历,缓存的值即为容纳最多水的值。
  4. 该题解使用for循环进行双指针遍历,相比while循环省了两行代码定义指针变量,建议还是使用for循环,代码更为精简。
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function (height) {
  let result = 0; // 缓存结果

  // 使用for循环遍历,可以省去两行声明指针代码,当i与j相遇时,退出循环
  for (let i = 0, j = height.length - 1; i < j; ) {
    // 查找较矮的高度,将其用于计算面积,之后将取值过的指针向内移动,继续遍历。
    const minHeight = height[i] < height[j] ? height[i++] : height[j--];
    // 计算当前面积,由于计算高度之后,指针已经移动过一次,此处宽度要加1
    const area = minHeight * (j - i + 1);
    // 对比当前面积和缓存的面积,保存最大值
    result = Math.max(area, result);
  }

  // 退出循环时,缓存的值就是最大值。
  return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant