其他分享
首页 > 其他分享> > 判断一个数组是不是另一个数组的子数组

判断一个数组是不是另一个数组的子数组

作者:互联网

简单来说,就是小的数组的元素是不是都是大的数组里面的

arr1: [1,2,3]
arr2: [3,4,5,1,3,2]
输出true

arr1: [1,2,3,3]
arr2: [3,4,5,1,3,2]
输出true

function isSubArr(a,b) {
    let big = []
    let small = []
    let set = new Set()
    if (a.length >= b.length) {
        big = a
        small = b
    } else {
        big = b
        small = a
    }
    for (let item of big) {
        set.add(item)
    }
    for (let i = 0; i < small.length; i++) {
        if (!set.has(small[i])) {
            return false
        }
    }
    return true
}
function isSubArr(a,b) {
    let big = []
    let small = []
    if (a.length >= b.length) {
        big = a
        small = b
    } else {
        big = b
        small = a
    }
    small = small.sort((a,b) => a - b)
    big = big.sort((a,b) => a - b)
    let slen = small.length
    let blen = big.length
    let i = 0, j = 0;
    while(i < slen && j < blen) {
        if (small[i] > big[j]) {
            if (j == blen - 1) {
                return false
            } else {
                j++
            }
        } else if (small[i] === b[j]) {
            i++
            j++
            while(i < slen && j < blen && small[i] === small[i - 1]) {
                i++
            }
            while(i < slen && j < blen && big[j] === big[j - 1]) {
                j++
            }
        } else {
            return false
        }
    }
    return true
}

https://blog.csdn.net/zxm317122667/article/details/83999828

标签:判断,++,big,是不是,length,let,数组,small,blen
来源: https://www.cnblogs.com/fazero/p/13737500.html