zl程序教程

您现在的位置是:首页 >  Java

当前栏目

集合的实现

2023-02-18 16:30:13 时间

前言


集合是没有重复值且有顺序的数据结构

实现思路和代码

集合类
function Set() {
  this.items = {}
}
基础集合具备以下方法
  • 判断元素是否在集合中
has(value) {
  //使用对象原型方法判断元素是否在集合中
  return this.items.hasOwnProperty(value)
}
  • 集合中添加元素
add(value) {
  //判断集合中是否存在要添加的元素
  if(this.has(value)) {
    return false
  }
  //添加元素到集合中
  this.items[value] = value
  return true
}
  • 删除集合中的元素
remove(value) {
  //判断集合中是否存在要删除的元素
  if(!this.has(value)) {
    return false
  }
  delete this.items[value]
  return trues
}
  • 清空集合
clear() {
  this.items = {}
}
  • 获取集合大小
size() {
  return Object.keys(this.items).length
}
  • 获取集合所有元素
values() {
  return Object.keys(this.items)
}

集合运算的实现

  • 并集运算
union(otherSet) {
  //创建新集合存储
  let unionSet = new Set()
  //获取当前集合的所有元素
  let values = this.values()
  //添加当前集合所有元素到新集合
  for(let i = 0; i < values.length; i++) {
    unionSet.add(values[i])
  }
  //重新赋值values
  values = otheret.values()
  //第二个集合所有元素添加到新集合
  for(let i = 0; i < values.lenght; i++) {
    unionSet.add(values[i])
  }
  return unionSet
}
  • 交集运算
intersection(otherSet) {
  //声明存储交集的集合
  let intersection = new Set()
  //获取当前集合所有元素
  let values = this.values()
  //遍历集合所有元素
  for(let i = 0; i < values.length; i++) {
    let item = values[i]
    //判断参数集合中是否存在当前元素 存在就添加到交集集合中
    if(otherSet.has(item)) {
      intersection.add(item)
    }
  }
  return intersection
}
  • 差集运算
difference(otherSet) {
  //声明差集集合
  let difference = new Set()
  //获取当前集合所有元素
  let values = this.values
  //遍历所有元素
  for(let i = 0; i < values.length; i++) {
    let item = values[i]
    //判断参数集合是否存在当前元素 不存在就添加到差集集合中
    if(!otherSet.has(item)) {
      difference.add(item)
    }
  }
  return difference
}
  • 子集运算
isSubsetOf(otherSet) {
  //当前集合大于参数集合直接返回false
  if(this.size() > otherSet.size()) return false
  //获取当前集合所有元素
  let values = this.values()
  //遍历所有元素
  for(let i = 0; i < values.length; i++) {
    //判断参数集合是否包含元素 不包含就说明当前集合不是参数集合的子集
    if(!otherSet.has(values[i])) {
      return false
    } 
  }
  return true
}

代码测试

let set = new Set()
set.add('swt')
set.add('mff')
console.log(set.has('swt'))
set.remove('swt')
console.log(set.values())
console.log(set.size())
set.clear()
console.log(set.values())
let other = new Set()
other.add('cyw')
other.add('swt')
console.log(set.union(other))
console.log(set.intersection(other))
console.log(set.difference(other))
console.log(set.isSubsetOf(other))