Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

【编程进阶】算法 — 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}]}`


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...