定义:

  1. 集合是由一组无序且唯一的项组成的
  2. 集合中的每个元素称为集合中的成员

成员特点

  1. 确定性: 成员是否在集合中是确定的
  2. 互异性: 集合中不能包含相同的元素
  3. 无序性: 集合中的成员是无序的

逻辑结构
集合结构: 集合内的成员是没有关联的

实现集合类

  1. class Set {
  2. constructor() {
  3. this.data = []
  4. }
  5. add(value) {
  6. if (!this.data.includes(value)) {
  7. this.data.push(value)
  8. }
  9. }
  10. findIndex(value) {
  11. return this.data.indexOf(value)
  12. }
  13. remove(value) {
  14. if (this.data.includes(value)) {
  15. this.data.splice(this.findIndex(value), 1)
  16. }
  17. return true
  18. }
  19. size() {
  20. return this.data.length
  21. }
  22. clear() {
  23. this.data = []
  24. }
  25. has(value) {
  26. return this.data.includes(value)
  27. }
  28. // 并集
  29. mergeSet(newSet) {
  30. newSet.forEach(item => {
  31. if (!this.data.has(item)) {
  32. this.data.push(item)
  33. }
  34. })
  35. }
  36. // 交集
  37. interSet(newSet) {
  38. return this.data.filter(item => newSet.has(item))
  39. }
  40. // 差集
  41. diffSet(newSet) {
  42. return this.data.filter(item => !newSet.has(item))
  43. }
  44. // 子集
  45. childSet(newSet) {
  46. return this.data.length !== newSet.data.length
  47. && newSet.data.every(item => this.data.includes(item))
  48. }
  49. // 补集
  50. complementSet(newSet) {
  51. if (!this.childSet(newSet)) {
  52. return false;
  53. }
  54. return this.diffSet(newSet)
  55. }
  56. }

JS中的 Set, 集合结构

  1. add/delete/has/clear/size
  2. keys/values/entries/forEach
  3. 数组去重,
    1. arr = [1,2,1,2,3];
    2. arr = [... new Set(arr)]

小结

  1. 集合的特点和逻辑结构
  2. 操作集合中的元素
  3. 求集合的并,差,交,补,子集
  4. js中的set

练习题

将一个N * N的数组实现从右上到左下打印

  1. const arr = [
  2. [1,2,3,4],
  3. [5,6,7,8],
  4. [9,10,11,12],
  5. [13,14,15,16]
  6. ]
  7. function rotateArr(arr) {
  8. let len = arr.length;
  9. let min = -len;
  10. for (let i = len - 1; i > min; i--) {
  11. let start = i;
  12. let result = []
  13. for (let j = 0; j < len; j++) {
  14. if (arr[j][start]) {
  15. result.push(arr[j][start])
  16. }
  17. start++
  18. }
  19. console.log(result.toString())
  20. }
  21. }
  22. /* 输出的结果为
  23. 4
  24. 3,8
  25. 2,7,12
  26. 1,6,11,16
  27. 5,10,15
  28. 9,14
  29. 13
  30. */