部分排序

给定一个整数数组,编写一个函数,找出索引m和n,只要将索引区间[m,n]的元素排好序,整个数组就是有序的。注意:n-m尽量最小,也就是说,找出符合条件的最短序列。函数返回值为[m,n],若不存在这样的m和n(例如整个数组是有序的),请返回[-1,-1]。

  先排序 再与原数组前后依次对比

const subSort = (array = [1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19]) => {
    const len = array.length
    const copy = [...array]
    copy.sort((x, y) => x - y)
    let start = 0
    let end = len - 1
    while (array[start] === copy[start] && start < len) {
        start++
    }
    while (array[end] === copy[end] && end > -1) {
        end--
    }
    if (start === len || end === -1) {
        return [-1, -1]
    }
    return [start, end]
};

  前后各找到不是按照升序、降序的排序的数组段 找出最大、小值 然后在原数组中找到其真正的下标位置

const subSort = (array = [5, 3, 1, 7, 9]) => {
    const len = array.length
    let start = -1,
        end = -1
    for (let i = 0; i < len - 1; i++) {
        const cv = array[i],
            nv = array[i + 1]
        if (cv > nv) {
            start = i
            break
        }
    }
    if (start === -1) return [-1, -1]
    for (let i = len - 1; i > 0; i--) {
        const cv = array[i],
            nv = array[i - 1]
        if (cv < nv) {
            end = i
            break
        }
    }
    if (end === -1) return [-1, -1]
    const sliceArray = array.slice(start, end + 1)
    const min = Math.min(...sliceArray)
    const max = Math.max(...sliceArray)
    const res = []
    for (let i = 0; i < len - 1; i++) {
        if (array[i] > min) {
            res.push(i)
            break
        }
    }
    for (let i = len - 1; i > -1; i--) {
        if (array[i] < max) {
            res.push(i)
            break
        }
    }
    return res
};

  

posted @ 2023-02-06 00:19  671_MrSix  阅读(12)  评论(0编辑  收藏  举报