定义:
- 集合是由一组无序且唯一的项组成的
- 集合中的每个元素称为集合中的成员
成员特点
- 确定性: 成员是否在集合中是确定的
- 互异性: 集合中不能包含相同的元素
- 无序性: 集合中的成员是无序的
逻辑结构
集合结构: 集合内的成员是没有关联的
实现集合类
class Set {constructor() {this.data = []}add(value) {if (!this.data.includes(value)) {this.data.push(value)}}findIndex(value) {return this.data.indexOf(value)}remove(value) {if (this.data.includes(value)) {this.data.splice(this.findIndex(value), 1)}return true}size() {return this.data.length}clear() {this.data = []}has(value) {return this.data.includes(value)}// 并集mergeSet(newSet) {newSet.forEach(item => {if (!this.data.has(item)) {this.data.push(item)}})}// 交集interSet(newSet) {return this.data.filter(item => newSet.has(item))}// 差集diffSet(newSet) {return this.data.filter(item => !newSet.has(item))}// 子集childSet(newSet) {return this.data.length !== newSet.data.length&& newSet.data.every(item => this.data.includes(item))}// 补集complementSet(newSet) {if (!this.childSet(newSet)) {return false;}return this.diffSet(newSet)}}
JS中的 Set, 集合结构
- add/delete/has/clear/size
- keys/values/entries/forEach
- 数组去重,
arr = [1,2,1,2,3];arr = [... new Set(arr)]
小结
- 集合的特点和逻辑结构
- 操作集合中的元素
- 求集合的并,差,交,补,子集
- js中的set
练习题
将一个N * N的数组实现从右上到左下打印
const arr = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]function rotateArr(arr) {let len = arr.length;let min = -len;for (let i = len - 1; i > min; i--) {let start = i;let result = []for (let j = 0; j < len; j++) {if (arr[j][start]) {result.push(arr[j][start])}start++}console.log(result.toString())}}/* 输出的结果为43,82,7,121,6,11,165,10,159,1413*/
