【编程进阶】算法 — js返回数组区间段数据

输入:[5,7,2,3,10,10, 15,17,19,10,1,7,2,1]
输出:

    result: {
        greaterThanTen:[{startIndex:0, endIndex:3}],
        lessThanTen:[
        {startIndex:6, endIndex:8},
        {startIndex:10, endIndex:13}]
    }

说明:

const arrs = [11,12,13,10,1,2,3,10,14,15,16,10,7,8,9]
已知arrs全是Number类型元素,假设有一个基数为10,那么大于10的索引0,1,2,8,9,10,小于10的索引4,5,6,12,13,14, 最终区间段的想要的结果为:`{greaterThan:[{startIndex:0, endIndex:2},{startIndex:8, endIndex:10}],
lessThan:[{startIndex:4, endIndex:6},{startIndex:12, endIndex:14}]}`

阅读 2.2k
1 个回答

image.png

interface Item {
    start: number,
    end: number,
}
interface Result {
    gt: Item[],
    lt: Item[],
    eq: number[],
}

const splitPieces = (arrs: number[], num: number) => {
    const result: Result = { gt: [], lt: [], eq: [] }
    let gt: Item | null = null;
    let lt: Item | null = null;
    for (let i = 0; i < arrs.length; i++) {
        const ele = arrs[i];
        if (ele === num) {
            gt = lt = null
            result.eq.push(i)
        } else if (ele > num) {
            lt = null
            if (!gt) {
                result.gt.push(gt = { start: i, end: i })
            } else {
                gt.end = i
            }
        } else {
            gt = null
            if (!lt) {
                result.lt.push(lt = { start: i, end: i })
            } else {
                lt.end = i
            }
        }
    }
    return result
}
console.log(splitPieces([11, 12, 13, 10, 1, 2, 3, 10, 14, 15, 16, 10, 7, 8, 9], 10))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏