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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短