JavaScript 中最短的未排序数组的长度

问题

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

我们的函数需要找到一个连续子数组的长度,这样如果我们只按升序对这个子数组进行排序,那么整个数组也将按升序排序。

例如,如果函数的输入是 -

const arr = [3, 7, 5, 9, 11, 10, 16];

那么输出应该是 -

const output = 5;

输出说明

因为如果我们对 [7, 5, 9, 11, 10] 进行排序,整个数组都会被排序。

示例

以下是代码 -

const arr = [3, 7, 5, 9, 11, 10, 16];
const shortestLength = (arr = []) => {
   const sorted = [...arr].sort((a, b) => a - b)
   let start = 0
   let end =sorted.length- 1
   while (sorted[start] === arr[start] && start < arr.length) {
      start += 1
   }
   while (sorted[end] === arr[end] && end >= 0) {
      end -= 1
   }
   return end >= start ? end - start + 1 : 0
}
console.log(shortestLength(arr));
输出结果

以下是控制台输出 -

5