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

更新於: 21-4-2021

86 次瀏覽

開啟您的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.