需要排序的最短子数组长度

Tags
algorithm
Created
Jul 3, 2020 5:12 AM

给定一个无序数组arr,求出需要排序的最短子数组的长度,对子数组排序后能使得整个数组有序,即为需要排序的数组。例如:arr=[1,5,3,4,2,6,7] 返回 4,因为只有 [5,3,4,2] 需要排序。

function len(arr) {
  const l = arr.length;
  let tempMax = 0;
  let tempMaxIndex = 0;
  let tempMin = Infinity;
  let tempMinIndex = l - 1;
  for(let i = 0; i < l; i++) {
    if (arr[i] > tempMax) {
        tempMax = arr[i];
    } else {
      tempMaxIndex = i;
    }
    if (arr[l - i - 1] > tempMin) {
      tempMinIndex = l - i - 1;
    } else {
      tempMin = arr[l - i - 1];
    }
  }
  console.log([arr[tempMinIndex], arr[tempMaxIndex]]);
  return tempMaxIndex - tempMinIndex + 1;
}
len([1,5,2,3,6,4,7]);
SuperMade with Super