Skip to content

Latest commit

 

History

History
107 lines (94 loc) · 2.15 KB

集合.md

File metadata and controls

107 lines (94 loc) · 2.15 KB

集合

集合是一种包含不同元素的数据结构。集合的特性:

  1. 集合中的成员是无序的。
  2. 集合中不允许相同成员存在。

集合的特性:

  • 不包含任何成员的集合称为空集,全集则是包含一切可能成员的集合。
  • 两个集合完成相同,则称两个集合相等。
  • 如果一个集合中所有的成员都属 于另外一个集合,则前 一集合称为后一集合的子集。

集合并在:

  1. 并集
  2. 交集
  3. 补集

手动实现Set

//添加集合元素
function add(data) {
  if (this.dataStore.indexOf(data) < 0) {
    this.dataStore.push(data)
    return true
  } else {
    return false
  }
}

// 删除该元素
function remove(data) {
  var pos = this.dataStore.indexOf(data)
  if (pos >  -1) {
    this.dataStore.indexOf(data)
    return true
  } else {
    return false
  }
}

// 显示全部成员
function show() {
  return this.dataStore
}

// 检查集合是否包含元素
function contains(data) {
  if (this.dataStore.indexOf(data) > -1) {
    return true
  } else {
    return false
  }
}

// 联合两个集合的并集
function 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
}

// 交集
function 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
}

// 非集
function difference(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
}

// 显示集合的大小
function size() {
  return this.dataStore.length
}

function Set() {
  this.dataStore = []
  this.add = add
  this.remove = remove
  this.size = size
  this.union = union
  this.intersect = intersect
  this.subset = subset
  this.difference = difference
  this.show = show
}