minjs1cn / weekly-learning

每周学习分享打卡
0 stars 0 forks source link

12-【leetcode】 盛最多水的容器 #12

Open Brand0n-Zhang opened 3 years ago

Brand0n-Zhang commented 3 years ago

https://leetcode-cn.com/problems/container-with-most-water/

Brand0n-Zhang commented 3 years ago
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    let result = 0
    let leftIndex = 0
    let rightIndex = height.length-1
    while (rightIndex > leftIndex) {
        let currentResult = getValue(leftIndex,rightIndex,height)
        result = Math.max(result,currentResult)
        // 决定水桶容积的是最短的木板,通过判断左右两块木板的高度,从最低的一块开始往中间收紧
        if (height[leftIndex] > height[rightIndex]) {
            rightIndex -- 
        }else{
            leftIndex ++
        }
    }
    return result
};
function getValue(leftIndex,rightIndex,arr) {
    return Math.min(arr[leftIndex],arr[rightIndex])*(rightIndex-leftIndex)
}
wucuiping commented 3 years ago

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(arr) {
    let l = 0 // 左指针的初始位置 
    let r = arr.length -1 // 右指针的初始位置
    let max = 0
    let cur = 0
    while(l < r) {
        cur = Math.min(arr[l], arr[r]) * (r - l)
        if (max < cur) {
            max = cur
        }
        if (arr[l] <= arr[r]) {
            ++l
        } else {
            --r
        }
    }
    return max
};
OceanApart commented 3 years ago
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function (height) {
  // 左右指针初始化指向最大边界,逐步缩小范围求最大范围
  let left = 0;
  let right = height.length - 1;
  // 最大面积
  let s = 0;
  // 宽度
  let w = 0;
  // 高度
  let h = 0;

  // 左右指针重叠时结束
  while (left < right) {
    w = right - left;
    // 较矮的作为高度
    h = Math.min(height[left], height[right]);
    s = Math.max(s, w * h);

    // 缩小范围
    // 如果「右侧」值大于「左侧」值
    // 如果左侧不动,移动右侧,不管新的右侧值大小如何,新的面积永远小于当前的面积
    // 因为左侧值相对较小,新的右侧值变大,高度取的也是左边;变小的话,高度变得更小;所以面积都是更小;
    // 所以只能移动左侧,缩小范围
    if (height[left] < height[right]) {
      left++;
    } else {
      // 反之移动右侧
      right--;
    }
  }

  return s;
};
wordlex commented 3 years ago
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    let res = 0, i = 0, j = height.length-1;
    while(i<j){
        let h = Math.min(height[i],height[j])
        let w = j - i
        res = Math.max(res,h*w)
        if(height[i]< height[j]) ++i
        else --j
    }
    return res
};