数据结构与算法之集合

集合

集合(set) 是一种包含不同元素的数据结构。 集合中的元素称为成员。

集合的两个最重要特性是: 首先, 集合中的成员是无序的; 其次, 集合中不允许相同成员存在。

对集合的三个操作

  • 并集

    将两个集合中的成员进行合并, 得到一个新集合。

  • 交集

    两个集合中共同存在的成员组成一个新的集合。

  • 补集

    属于一个集合而不属于另一个集合的成员组成的集合。

直接上代码。还是用ES6原生的Set比较方便。

function Set(){
    this.dataStore = [];
}

Set.prototype = {
    constructor: Set,
    add(data){
        if(this.dataStore.indexOf(data)<0){
            this.dataStore.push(data);
            return true;
        }else{
            return false;
        }
    },
    remove(data){
        var pos = this.dataStore.indexOf(data);
        if(pos > -1){
            this.dataStore.splice(pos, 1);
            return true;
        }else{
            return false;
        }
    },
    size(){
        return this.dataStore.length;
    },

    //执行并集操作,不影响操作的两个set,返回一个新的set
    union(set){
        var tempSet = new Set();
        for(var i = 0;i<this.dataStore.length;i++){
            tempSet.add(this.dataStore[i]);
        }
        for(var i = 0;i<set.dataStore.length;i++){
            if(!tempSet.contains(set.dataStore[i])){
                tempSet.dataStore.push(set.dataStore[i]);
            }
        }
        return tempSet;
    },

    //执行交集操作
    intersect(set){
        var tempSet = new Set();
        for(var i = 0;i<this.dataStore.length;i++){
            if(set.contains(this.dataStore[i])){
                tempSet.add(this.dataStore[i]);
            }
        }
        return tempSet;
    },

    //判断本set是否为传参set的一个子集
    subset(set){
        if(this.size() > set.size()) return false;
        for(var i of this.dataStore){
            if(!set.contains(i)) return false;
        }
        return true
    },

    //执行补集操作,保存属于本set不属于传参set的成员
    difference(set){
        var tempSet = new Set();
        for(var i of this.dataStore){
            if(!set.contains(i)){
                tempSet.add(i);
            }
        }
        return tempSet;
    },
    show(){
        return this.dataStore;
    },
    contains(data){
        return this.dataStore.indexOf(data) > -1;
    }
}

猜你喜欢

转载自www.cnblogs.com/simpul/p/11027184.html
今日推荐