Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...