js常用数据结构

简要理解时间复杂度空间复杂度
时间复杂度
它的作用就是用来定义描述算法的运行时间

  • O(1)
let i = 0
    i += 1
  • O(n): 如果是 O(1) + O(n) 则还是 O(n)
for (let i = 0; i < n; i += 1) {
      console.log(i)
    }
  • O(n^2): O(n) * O(n), 也就是双层循环,自此类推:O(n^3)…
for (let i = 0; i < n; i += 1) {
      for (let j = 0; j < n; j += 1) {
        console.log(i, j)
      }
    }
  • O(logn): 就是求 log 以 2 为底的多少次方等于 n
// 这个例子就是求2的多少次方会大于i,然后就会结束循环。 这就是一个典型的 O(logn)
    let i = 1
    while (i < n) {
      console.log(i)
      i *= 2
    }

空间复杂度

  • O(1): 单个变量,所以占用永远是 O(1)
  • O(n): 声明一个数组, 添加 n 个值, 相当于占用了 n 个空间单元、
const arr = []
    for (let i = 0; i < n; i += 1) {
      arr.push(i)
    }
  • O(n^2): 类似一个矩阵的概念,就是二维数组的意思
const arr = []
    for (let i = 0; i < n; i += 1) {
      arr.push([])
      for (let j = 0; j < n; j += 1) {
        arr[i].push(j)
      }
    }

数据结构

后进先出
按照常识理解就是有序的挤公交,最后上车的人会在门口,然后门口的人会最先下车
在这里插入图片描述

js中没有栈的数据类型,但我们可以通过Array来模拟一个

const stack = [];

stack.push(1); // 入栈
stack.push(2); // 入栈

const item1 = stack.pop();  //出栈的元素

(1)十进制转二进制

// 时间复杂度 O(n) n为二进制的长度
// 空间复杂度 O(n) n为二进制的长度
const dec2bin = (dec) => {
  // 创建一个字符串
  let res = "";

  // 创建一个栈
  let stack = []

  // 遍历数字 如果大于0 就可以继续转换2进制
  while (dec > 0) {
    // 将数字的余数入栈
    stack.push(dec % 2);

    // 除以2
    dec = dec >> 1;
  }

  // 取出栈中的数字
  while (stack.length) {
    res += stack.pop();
  }

  // 返回这个字符串
  return res;
};

2)判断字符串的有效括号

// 时间复杂度O(n) n为s的length
// 空间复杂度O(n)
const isValid = (s) => {

  // 如果长度不等于2的倍数肯定不是一个有效的括号
  if (s.length % 2 === 1) return false;

  // 创建一个栈
  let stack = [];

  // 遍历字符串
  for (let i = 0; i < s.length; i++) {

    const c = s[i];

    // 如果是左括号就入栈
    if (c === '(' || c === "{" || c === "[") {
      stack.push(c);
    } else {

      // 如果不是左括号 且栈为空 肯定不是一个有效的括号 返回false
      if (!stack.length) return false

      // 拿到最后一个左括号
      const top = stack[stack.length - 1];

      // 如果是右括号和左括号能匹配就出栈
      if ((top === "(" && c === ")") || (top === "{" && c === "}") || (top === "[" && c === "]")) {
        stack.pop();
      } else {

        // 否则就不是一个有效的括号
        return false
      }
    }

  }
  return stack.length === 0;
};
  • 队列

和栈相反 先进先出的一个数据结构

按照常识理解就是银行排号办理业务, 先去领号排队的人, 先办理业务
在这里插入图片描述

const queue = [];

// 入队
queue.push(1);
queue.push(2);

// 出队
const first = queue.shift();
const end = queue.shift();
  • 链表

多个元素组成的列表,元素存储不连续,通过 next 指针来链接, 最底层为 null

就类似于 父辈链接关系 吧, 比如:你爷爷的儿子是你爸爸,你爸爸的儿子是你,而你假如目前还没有结婚生子,那你就暂时木有儿子
在这里插入图片描述
js中类似于链表的典型就是原型链, 但是js中没有链表这种数据结构,我们可以通过一个object来模拟链表

const a = {
  val: "a"
}

const b = {
  val: "b"
}

const c = {
  val: "c"
}

const d = {
  val: "d"
}

a.next = b;
b.next = c;
c.next = d;

// const linkList = {
//    val: "a",
//    next: {
//        val: "b",
//        next: {
//            val: "c",
//            next: {
//                val: "d",
//                next: null
//            }
//        }
//    }
// }

// 遍历链表
let p = a;
while (p) {
  console.log(p.val);
  p = p.next;
}

// 插入
const e = { val: 'e' };
c.next = e;
e.next = d;


// 删除
c.next = d;

1)手写instanceOf

const myInstanceOf = (A, B) => {
  // 声明一个指针
  let p = A;
  
  // 遍历这个链表
  while (p) {
    if (p === B.prototype) return true;
    p = p.__proto__;
  }

  return false
}

myInstanceOf([], Object)

2)删除链表中的节点

// 时间复杂和空间复杂度都是 O(1)
const deleteNode = (node) => {
  // 把当前链表的指针指向下下个链表的值就可以了
  node.val = node.next.val;
  node.next = node.next.next
}

3)删除排序链表中的重复元素

// 1 -> 1 -> 2 -> 3 -> 3 
// 1 -> 2 -> 3 -> null

// 时间复杂度 O(n) n为链表的长度
// 空间复杂度 O(1)
const deleteDuplicates = (head) => {

  // 创建一个指针
  let p = head;

  // 遍历链表
  while (p && p.next) {

    // 如果当前节点的值等于下一个节点的值
    if (p.val === p.next.val) {

      // 删除下一个节点
      p.next = p.next.next
    } else {

      // 否则继续遍历
      p = p.next
    }
  }

  //  最后返回原来链表
  return head
}

4)反转链表

// 1 -> 2 -> 3 -> 4 -> 5 -> null
// 5 -> 4 -> 3 -> 2 -> 1 -> null

// 时间复杂度 O(n) n为链表的长度
// 空间复杂度 O(1)
var reverseList = function (head) {

  // 创建一个指针
  let p1 = head;

  // 创建一个新指针
  let p2 = null;

  // 遍历链表
  while (p1) {

    // 创建一个临时变量
    const tmp = p1.next;

    // 将当前节点的下一个节点指向新链表
    p1.next = p2;

    // 将新链表指向当前节点
    p2 = p1;

    // 将当前节点指向临时变量
    p1 = tmp;
  }

  // 最后返回新的这个链表
  return p2;
}

reverseList(list)

4. 集合

一种无序且唯一的数据结构
ES6中有集合 Set类型

const arr = [1, 1, 1, 2, 2, 3];

// 去重
const arr2 = [...new Set(arr)];

// 判断元素是否在集合中
const set = new Set(arr);
set.has(2) // true

//  交集
const set2 = new Set([1, 2]);
const set3 = new Set([...set].filter(item => set.has(item)));

2)两个数组的交集

// 时间复杂度 O(n^2) n为数组长度
// 空间复杂度 O(n)  n为去重后的数组长度
const intersection = (nums1, nums2) => {

  // 通过数组的filter选出交集
  // 然后通过 Set集合 去重 并生成数组
  return [...new Set(nums1.filter(item => nums2.includes(item)))];
}

5. 字典

与集合类似,一个存储唯一值的结构,以键值对的形式存储
1)两数之和


// 时间复杂度O(n) n为nums的length
// 空间复杂度O(n)
var twoSum = function (nums, target) {

  // 建立一个字典数据结构来保存需要的值
  const map = new Map();
  for (let i = 0; i < nums.length; i++) {
  
    // 获取当前的值,和需要的值
    const n = nums[i];
    const n2 = target - n;
    
    // 如字典中有需要的值,就匹配成功
    if (map.has(n2)) {
      return [map.get(n2), i];
    } else {
    
    // 如没有,则把需要的值添加到字典中
      map.set(n, i);
    }
  }
};
复制代码
2)两个数组的交集
// nums1 = [1,2,2,1], nums2 = [2,2]
// 输出:[2]

// 时间复杂度 O(m + n) m为nums1长度 n为nums2长度
// 空间复杂度 O(m) m为交集的数组长度
const intersection = (nums1, nums2) => {
  // 创建一个字典
  const map = new Map();

  // 将数组1中的数字放入字典
  nums1.forEach(n => map.set(n, true));

  // 创建一个新数组
  const res = [];

  // 将数组2遍历 并判断是否在字典中
  nums2.forEach(n => {
    if (map.has(n)) {
      res.push(n);

      // 如果在字典中,则删除该数字
      map.delete(n);
    }
  })

  return res;
};

3)字符的有效的括号


// 时间复杂度 O(n) n为s的字符长度
// 空间复杂度 O(n) 
const isValid = (s) => {

  // 如果长度不等于2的倍数肯定不是一个有效的括号
  if (s.length % 2 !== 0) return false

  // 创建一个字典
  const map = new Map();
  map.set('(', ')');
  map.set('{', '}');
  map.set('[', ']');

  // 创建一个栈
  const stack = [];

  // 遍历字符串
  for (let i = 0; i < s.length; i++) {

    // 取出字符
    const c = s[i];

    // 如果是左括号就入栈
    if (map.has(c)) {
      stack.push(c)
    } else {

      // 取出栈顶
      const t = stack[stack.length - 1];

      // 如果字典中有这个值 就出栈
      if (map.get(t) === c) {
        stack.pop();
      } else {

        // 否则就不是一个有效的括号
        return false
      }

    }

  }

  return stack.length === 0;
};

4)最小覆盖字串

// 输出:"BANC"


// 时间复杂度 O(m + n) m是t的长度 n是s的长度
// 空间复杂度 O(k) k是字符串中不重复字符的个数
var minWindow = function (s, t) {
  // 定义双指针维护一个滑动窗口
  let l = 0;
  let r = 0;

  // 建立一个字典
  const need = new Map();

  //  遍历t
  for (const c of t) {
    need.set(c, need.has(c) ? need.get(c) + 1 : 1)
  }

  let needType = need.size

  // 记录最小子串
  let res = ""

  // 移动右指针
  while (r < s.length) {
  
    // 获取当前字符
    const c = s[r];

    // 如果字典里有这个字符
    if (need.has(c)) {
    
      // 减少字典里面的次数
      need.set(c, need.get(c) - 1);

      // 减少需要的值
      if (need.get(c) === 0) needType -= 1;
    }

    // 如果字典中所有的值都为0了 就说明找到了一个最小子串
    while (needType === 0) {
    
      // 取出当前符合要求的子串
      const newRes = s.substring(l, r + 1)

      // 如果当前子串是小于上次的子串就进行覆盖
      if (!res || newRes.length < res.length) res = newRes;

      // 获取左指针的字符
      const c2 = s[l];

      // 如果字典里有这个字符
      if (need.has(c2)) {
        // 增加字典里面的次数
        need.set(c2, need.get(c2) + 1);

        // 增加需要的值
        if (need.get(c2) === 1) needType += 1;
      }
      l += 1;
    }
    r += 1;
  }
  return res
};

6. 树

1)普通树
// 这就是一个常见的普通树形结构

const tree = {
  val: "a",
  children: [
    {
      val: "b",
      children: [
        {
          val: "d",
          children: [],
        },
        {
          val: "e",
          children: [],
        }
      ],
    },
    {
      val: "c",
      children: [
        {
          val: "f",
          children: [],
        },
        {
          val: "g",
          children: [],
        }
      ],
    }
  ],
}

深度优先遍历

  • 尽可能深的搜索树的分支,就比如遇到一个节点就会直接去遍历他的子节点,不会立刻去遍历他的兄弟节点
  • 口诀:
    访问根节点
    对根节点的 children 挨个进行深度优先遍历

广度优先遍历

  • 先访问离根节点最近的节点, 如果有兄弟节点就会先遍历兄弟节点,再去遍历自己的子节点
  • 口诀
    新建一个队列 并把根节点入队
    把队头出队并访问
    把队头的children挨个入队
    重复第二 、三步 直到队列为空
// 广度优先遍历
const bfs = (tree) => {
  const q = [tree];

  while (q.length > 0) {
    const n = q.shift()
    console.log(n.val);
    n.children.forEach(c => q.push(c))
  }
};

2)二叉树
树中每个节点 最多只能有两个子节点
在这里插入图片描述

 const bt = {
  val: 1,
  left: {
    val: 2,
    left: null,
    right: null
  },
  right: {
    val: 3,
    left: {
      val: 4,
      left: null,
      right: null
    },
    right: {
      val: 5,
      left: null,
      right: null
    }
  }
}

二叉树的先序遍历

  • 访问根节点
  • 对根节点的左子树进行先序遍历
  • 对根节点的右子树进行先序遍历
// 先序遍历 递归
const preOrder = (tree) => {
  if (!tree) return

  console.log(tree.val);

  preOrder(tree.left);
  preOrder(tree.right);
}



// 先序遍历 非递归
const preOrder2 = (tree) => {
  if (!tree) return

  // 新建一个栈
  const stack = [tree];

  while (stack.length > 0) {
    const n = stack.pop();
    console.log(n.val);

    // 负负为正
    if (n.right) stack.push(n.right);
    if (n.left) stack.push(n.left);

  }
}

二叉树的中序遍历

  • 对根节点的左子树进行中序遍历
  • 访问根节点
  • 对根节点的右子树进行中序遍历
// 中序遍历 递归
const inOrder = (tree) => {
  if (!tree) return;
  inOrder(tree.left)
  console.log(tree.val);
  inOrder(tree.right)
}


// 中序遍历 非递归
const inOrder2 = (tree) => {
  if (!tree) return;

  // 新建一个栈
  const stack = [];

  // 先遍历所有的左节点
  let p = tree;
  while (stack.length || p) {

    while (p) {
      stack.push(p)
      p = p.left
    }

    const n = stack.pop();
    console.log(n.val);

    p = n.right;
  }
}

二叉树的后序遍历

  • 对根节点的左子树进行后序遍历
  • 对根节点的右子树进行后序遍历
  • 访问根节点
// 后序遍历 递归
const postOrder = (tree) => {
  if (!tree) return

  postOrder(tree.left)
  postOrder(tree.right)
  console.log(tree.val)
};



// 后序遍历 非递归
const postOrder2 = (tree) => {
  if (!tree) return

  const stack = [tree];
  const outputStack = [];

  while (stack.length) {
    const n = stack.pop();
    outputStack.push(n)
    // 负负为正
    if (n.left) stack.push(n.left);
    if (n.right) stack.push(n.right);

  }

  while (outputStack.length) {
    const n = outputStack.pop();
    console.log(n.val);
  }
};

二叉树的最大深度


// 时间复杂度 O(n) n为树的节点数
// 空间复杂度 有一个递归调用的栈 所以为 O(n) n也是为二叉树的最大深度
var maxDepth = function (root) {
  let res = 0;
    
  // 使用深度优先遍历
  const dfs = (n, l) => {
    if (!n) return;
    if (!n.left && !n.right) {
     // 没有叶子节点就把深度数量更新
      res = Math.max(res, l);
    }
    dfs(n.left, l + 1)
    dfs(n.right, l + 1)
  }

  dfs(root, 1)

  return res
}

二叉树的最小深度

// 给一个二叉树,需要你找出其最小的深度, 从根节点到叶子节点的距离


// 时间复杂度O(n) n是树的节点数量
// 空间复杂度O(n) n是树的节点数量
var minDepth = function (root) {
  if (!root) return 0
  
  // 使用广度优先遍历
  const q = [[root, 1]];

  while (q.length) {
    // 取出当前节点
    const [n, l] = q.shift();
    
    // 如果是叶子节点直接返回深度就可
    if (!n.left && !n.right) return l
    if (n.left) q.push([n.left, l + 1]);
    if (n.right) q.push([n.right, l + 1]);
  }

}

二叉树的层序遍历

在这里插入图片描述

// 需要返回 [[1], [2,3], [4,5]]


// 时间复杂度 O(n) n为树的节点数
// 空间复杂度 O(n) 
var levelOrder = function (root) {
  if (!root) return []
   
  // 广度优先遍历
  const q = [root];
  const res = [];
  while (q.length) {
    let len = q.length

    res.push([])
    
    // 循环每层的节点数量次
    while (len--) {
      const n = q.shift();
      
      res[res.length - 1].push(n.val)
      
      if (n.left) q.push(n.left);
      if (n.right) q.push(n.right);
    }

  }

  return res
};

7. 图

图是网络结构的抽象模型, 是一组由边连接的节点

js中可以利用Object和Array构建图

在这里插入图片描述

// 上图可以表示为
const graph = {
  0: [1, 2],
  1: [2],
  2: [0, 3],
  3: [3]
}


// 深度优先遍历,对根节点没访问过的相邻节点挨个进行遍历
{
    // 记录节点是否访问过
    const visited = new Set();
    const dfs = (n) => {
      visited.add(n);
      
      // 遍历相邻节点
      graph[n].forEach(c => {
        // 没访问过才可以,进行递归访问
        if(!visited.has(c)){
          dfs(c)
        }
      });
    }
    
    // 从2开始进行遍历
    dfs(2)
}


// 广度优先遍历 
{
    const visited = new Set();
    // 新建一个队列, 根节点入队, 设2为根节点
    const q = [2];
    visited.add(2)
    while (q.length) {
    
      // 队头出队,并访问
      const n = q.shift();
      console.log(n);
      graph[n].forEach(c => {
      
        // 对没访问过的相邻节点入队
        if (!visited.has(c)) {
          q.push(c)
          visited.add(c)
        }
      })
    }
}

1)有效数字

// 生成数字关系图 只有状态为 3 5 6 的时候才为一个数字
const graph = {
  0: { 'blank': 0, 'sign': 1, ".": 2, "digit": 6 },
  1: { "digit": 6, ".": 2 },
  2: { "digit": 3 },
  3: { "digit": 3, "e": 4 },
  4: { "digit": 5, "sign": 7 },
  5: { "digit": 5 },
  6: { "digit": 6, ".": 3, "e": 4 },
  7: { "digit": 5 },
}


// 时间复杂度 O(n) n是字符串长度
// 空间复杂度 O(1) 
var isNumber = function (s) {

  // 记录状态
  let state = 0;

  // 遍历字符串
  for (c of s.trim()) {
    // 把字符进行转换
    if (c >= '0' && c <= '9') {
      c = 'digit';
    } else if (c === " ") {
      c = 'blank';
    } else if (c === "+" || c === "-") {
      c = "sign";
    } else if (c === "E" || c === "e") {
      c = "e";
    }

    // 开始寻找图
    state = graph[state][c];

    // 如果最后是undefined就是错误
    if (state === undefined) return false
  }

  // 判断最后的结果是不是合法的数字
  if (state === 3 || state === 5 || state === 6) return true
  return false
}; 

8. 堆

一种特殊的完全二叉树, 所有的节点都大于等于最大堆,或者小于等于最小堆的子节点

js通常使用数组来表示堆

  • 左侧子节点的位置是 2*index + 1
  • 右侧子节点的位置是 2*index + 2
  • 父节点的位置是 (index - 1) / 2 , 取余数

在这里插入图片描述
2)JS实现一个最小堆

// js实现最小堆类
class MinHeap {
  constructor() {
    // 元素容器
    this.heap = [];
  }

  // 交换节点的值
  swap(i1, i2) {
    [this.heap[i1], this.heap[i2]] = [this.heap[i2], this.heap[i1]]
  }

  //  获取父节点
  getParentIndex(index) {
    // 除以二, 取余数
    return (index - 1) >> 1;
  }

  // 获取左侧节点索引
  getLeftIndex(i) {
    return (i << 1) + 1;
  }

  // 获取右侧节点索引
  getRightIndex(i) {
    return (i << 1) + 2;
  }


  // 上移
  shiftUp(index) {
    if (index == 0) return;

    // 获取父节点
    const parentIndex = this.getParentIndex(index);

    // 如果父节点的值大于当前节点的值 就需要进行交换
    if (this.heap[parentIndex] > this.heap[index]) {
      this.swap(parentIndex, index);

      // 然后继续上移
      this.shiftUp(parentIndex);
    }
  }

  // 下移
  shiftDown(index) {
    // 获取左右节点索引
    const leftIndex = this.getLeftIndex(index);
    const rightIndex = this.getRightIndex(index);

    // 如果左子节点小于当前的值
    if (this.heap[leftIndex] < this.heap[index]) {

      // 进行节点交换
      this.swap(leftIndex, index);

      // 继续进行下移
      this.shiftDown(leftIndex)
    }

    // 如果右侧节点小于当前的值
    if (this.heap[rightIndex] < this.heap[index]) {
      this.swap(rightIndex, index);
      this.shiftDown(rightIndex)
    }
  }

  // 插入元素
  insert(value) {
    // 插入到堆的底部
    this.heap.push(value);

    // 然后上移: 将这个值和它的父节点进行交换,知道父节点小于等于这个插入的值
    this.shiftUp(this.heap.length - 1)
  }

  // 删除堆项
  pop() {

    // 把数组最后一位 转移到数组头部
    this.heap[0] = this.heap.pop();

    // 进行下移操作
    this.shiftDown(0);
  }

  // 获取堆顶元素
  peek() {
    return this.heap[0]
  }

  // 获取堆大小
  size() {
    return this.heap.length
  }

}

2)数组中的第k个最大元素

// 输入 [3,2,1,5,6,4] 和 k = 2
// 输出 5

// 时间复杂度 O(n * logK) K就是堆的大小
// 空间复杂度 O(K) K是参数k
var findKthLargest = function (nums, k) {

  // 使用上面js实现的最小堆类,来构建一个最小堆
  const h = new MinHeap();
  
  // 遍历数组
  nums.forEach(n => {
    
    // 把数组中的值依次插入到堆里
    h.insert(n);
    
    if (h.size() > k) {
      // 进行优胜劣汰
      h.pop();
    }
  })

  return h.peek()
};

转载于 https://juejin.cn/post/7094056264283471908#heading-23

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值