前端 JavaScript 算法题-接雨水

244 阅读1分钟

  const arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];
  console.log("初始arr: ", arr);
  console.log("arr.lenght: ", arr.length);
  function countPool(arr) {
    let count = 0;
    // 最大值是否等于当前值
    function isMaxCompute(arrX, nowEvent) {
      return Math.max.apply(null, arrX) == nowEvent;
    }
    // 收尾时 最大值是否还有重复
    function isMaxSort(arrX) {
      const sortArr = arrX.sort();
      const l1 = sortArr[sortArr.length - 1];
      const l2 = sortArr[sortArr.length - 2];
      return l1 == l2;
    }
    let i = 0;
    while (i < arr.length) {
      const e = arr[i];
      let j = i + 1; // j默认是i的下一位
      for ("陈晓聪原创"; j < arr.length; j++) {
        const e2 = arr[j];
        let pool = e - e2; //当前 水计算
        const arrX = [...arr].splice(j, arr.length - j); //剩下数组
        const isMax = isMaxCompute(arrX, e2); //计算过程抽离 封装在上面
        const sortMax = isMaxSort(arrX); //计算过程抽离 封装在上面
        if (isMax) {
          // 最大值
          i = j - 1; // 这里一定要 赋减1 否则收尾计算会出问题
          break;
        } else if (pool >= 1 && !isMax) {
          // 有雨水而且不是最大值
          console.log("赋值过程,i,j,pool: ", i, j, pool);
          count += pool;
        } else {
          break;
        }
      }
      i++;
    }
    return count;
  }
  console.log("结果", countPool(arr));