在 JavaScript 中查找到下一个较大元素的距离

javascriptweb developmentfront end technology

问题

我们需要编写一个 JavaScript 函数,该函数将数字数组 arr 作为第一个也是唯一的参数。

我们的函数应该为输入构建一个新数组,其中每个对应元素都是到比当前元素更大的下一个元素的距离,如果当前元素右侧没有更大的元素,我们应该将 res 数组中该对应元素的 0 推送到最后,我们应该返回这个数组。

例如,如果函数的输入是

输入

const arr = [12, 13, 14, 11, 16, 10, 12, 17, 19, 18];

输出

const output = [1, 1, 2, 1, 3, 1, 1, 1, 0, 0];

输出说明

因为 12 的下一个更大元素是 13,相距 1 个区块,

13 的下一个更大元素是 14,相距 1 个区块,

14 的下一个更大元素是 16,相距 2 个区块,依此类推。

以下是代码 −

示例

const arr = [12, 13, 14, 11, 16, 10, 12, 17, 19, 18];
const findNextGreater = (arr = []) => {
   const stack = []
   const res = new Array(arr.length).fill(0)
   for (let i = 0; i < arr.length; i++) {
      while (arr[i] > arr[stack[stack.length - 1]] && stack.length > 0) {
         const index = stack.pop()
         res[index] = i - index
      }
      stack.push(i)
   };
   return res
};
console.log(findNextGreater(arr));

输出

[1, 1, 2, 1, 3, 1, 1, 1, 0, 0]

相关文章