前端算法

99 阅读3分钟

检测括弧

截屏2023-12-13下午1.32.57.png

  const isValid = function (s){
    const stack = []
    consr map = new Map()
    map.set('(',')')
    map.set('{','}')
    map.set('[',']')
    //([])   [([]
    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
}

console.log(isValid('[()]))'))

排序

选择排序

截屏2023-12-08下午3.47.30.png

Array.prototype.selectionSort = function () {
    debugger
  for(let i =0;i<this.length-1;i++){
    let min = i
    for(let j = i+1;j<this.length;j++){
        if(this[j]<this[min]){
            min = j
        }
    }
    if(this[i]!==this[min]){
        const temp = this[i]
    this[i] = this[min]
    this[min] = temp
    }
    
  }
};

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

arr.selectionSort();
console.log(arr)

插入排序

截屏2023-12-08下午5.00.08.png

Array.prototype.selectionSort = function () {
 
  for(let i =1;i<this.length;i++){
   let temp = this[i],
   j = i
   while(j>0){
    if(this[j-1]>temp){
        this[j]=this[j-1]
    }else{
        break;
    }
    j--
   }
    this[j] = temp
  }
};

const arr = [10,30,25,5,2];
    
arr.selectionSort();
console.log(arr)

归并排序

Array.prototype.mergeSort = function () {
    const rec = (arr) => {
        if (arr.length === 1) { return arr; }
        const mid = Math.floor(arr.length / 2);
        const left = arr.slice(0, mid);
        const right = arr.slice(mid, arr.length);
        const orderLeft = rec(left);
        const orderRight = rec(right);
        const res = [];
        while (orderLeft.length || orderRight.length) {
            if (orderLeft.length && orderRight.length) {
                res.push(orderLeft[0] < orderRight[0] ? orderLeft.shift() : orderRight.shift());
            } else if (orderLeft.length) {
                res.push(orderLeft.shift());
            } else if (orderRight.length) {
                res.push(orderRight.shift());
            }
        }
        return res;
    };
    const res = rec(this);
    res.forEach((n, i) => { this[i] = n; });
};

const arr = [5, 4, 3, 2, 1];
arr.mergeSort();



快速排序

截屏2023-12-11下午3.37.21.png

Array.prototype.quickSort = function () {
    debugger
    const rec = (arr) => {
        if (arr.length === 1) { return arr; }
        const left = [];
        const right = [];
        const mid = arr[0];
        for (let i = 1; i < arr.length; i += 1) {
            if (arr[i] < mid) {
                left.push(arr[i]);
            } else {
                right.push(arr[i]);
            }
        }           
        return [...rec(left), mid, ...rec(right)];
    };
    const res = rec(this);
    res.forEach((n, i) => { this[i] = n });
};

const arr = [2, 4, 5, 3, 1];
arr.quickSort();
console.log(arr)

二分法

Array.prototype.binarySearch = function (item) {
    let high=this.length-1,
    low = 0;
    while(low <=high){
        const mid = Math.floor((high-low)/2)
        if(this[mid]<item){
            low=mid+1
        }else if(this[mid]>item){
            high =mid-1
        }else{
            return mid
        }
    }
    return -1
};

const arr = [2,3,5,8,10];
arr.binarySearch();

字典

两个数组交集

截屏2023-12-14下午10.19.02.png

 function search(arr1,arr2){
   const map = new Map()
   const result = []
   arr1.forEach(item => {
    map.set(item,true)
   });
   arr2.forEach((item)=>{
    if(map.get(item)){
        result.push(item)
        map.delete(item)
    }
   })
   return result
 }
 let arr1  = [1,2,2,1]
 let arr2=[2,2]
console.log(search(arr1,arr2))

两数之和

截屏2023-12-15下午7.51.18.png

截屏2023-12-15下午8.07.18.png

function search(arr,target){
   let map = new Map()
  for(let i = 0;i<arr.length;i++){
    let value = target-arr[i]
    if(map.has(value)){
        return [map.get(value),i]
    }else{
        map.set(arr[i],i)
    }
  }
}
let nums=[2,7,11,15]
console.log(search(nums,18))

无重复字符的最长子串

截屏2023-12-16下午3.59.57.png

  function search(s){
    let l = 0,
    map = new Map(),
    res = 0;
    for(let r=0;r<s.length;r++){
        if(map.has(s[r])&&map.get(s[r])>=l){
            l = map.get(s[r])+1
        }else{
            map.set(s[r],r)
        }
        res = Math.max(res,r-l+1)
    }
    return res
  }
console.log(search('abbcdea'))

最小覆盖子串

截屏2023-12-21下午2.29.26.png

截屏2023-12-21下午2.34.12.png

function search(s,t){
  let l =0;
  let r =0;
  let res = 0
  const need = new Map()
  for(let c of t){
    need.set(c,need.has(c)?need.get(c)+1:1)
  }
  let needType = need.size;
  debugger
  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
    }
    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

  }
const s = 'AADOBECODEBANC'
const t = 'ABC'
console.log(search(s,t))

截屏2023-12-23下午12.29.55.png

深度优先

截屏2023-12-23下午3.03.18.png

深度优先遍历

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

const dfs = (root) => {
  console.log(root.val);
  root.children.forEach((child)=>{dfs(child)});
};

dfs(tree);

二叉树的最大深度

 const root = {
            val: 3,
            left: {
                val: 9,
                left: {
                    val: null,
                    left: null,
                    right: null,
                },
                right: {
                    val: null,
                    left: null,
                    right: null,
                },
            },
            right: {
                val: 20,
                left: {
                    val: 15,
                    left: null,
                    right: null,
                },
                right: {
                    val: 7,
                    left: null,
                    right: null,
                },
            },
        };
        
 function deep() {
            let res = 0;
            const bfs = (root, l) => {
                if (!root) { return }
                if(!root.left&&!root.right){
                    res = Math.max(res, l)
                }
                
                bfs(root.left, l + 1)
                bfs(root.right, l + 1)

            }
            bfs(root, 1)
        }

广度优先

截屏2023-12-23下午3.20.59.png

实现广度优先

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

const bfs = (root) => {
  const q = [root];
  while (q.length > 0) {
      const n = q.shift();
      console.log(n.val);
      n.children.forEach(child => {
          q.push(child);
      });
  }
};

bfs(tree);

二叉树的最小深度

截屏2023-12-30下午5.35.14.png

   const bt = {
            val: 3,
            left: {
                val: 9,
                left: {
                    val: 1,
                    left: null,
                    right: null,
                },
                right: {
                    val: 2,
                    left: null,
                    right: null,
                },
            },
            right: {
                val: 20,
                left: {
                    val: 15,
                    left: null,
                    right: null,
                },
                right: {
                    val: 7,
                    left: null,
                    right: null,
                },
            },
        };
        function deep(bt, l) {
            if (!bt) { return 0 }
            let root = [[bt, l]]
            while (root.length > 0) {

                let [item, l] = root.shift()
                console.log(item.val, l)
                if (!item.left && !item.right) {
                    return l
                }
                item.left && root.push([item.left, l + 1])
                item.right && root.push([item.right, l + 1])
            }
        }
        console.log(deep(bt, 1))

二叉树

截屏2023-12-25下午2.44.12.png

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

先序遍历

截屏2023-12-25下午2.49.30.png

const preorder = (root)=>{
    if(!root)return
    console.log(root.val)
    preorder(root.left)
    preorder(root.right)
}
preorder(bt)

截屏2023-12-25下午3.30.43.png

中序遍历

截屏2023-12-25下午3.32.20.png

const inorder = (root)=>{
    if(!root)return
    inorder(root.left)
    console.log(root.val)
    inorder(root.right)

}
inorder(bt)

截屏2023-12-25下午4.00.48.png

后序遍历

截屏2023-12-25下午4.09.54.png

const postorder = (root) => {
    if (!root) { return; }
    postorder(root.left);
    postorder(root.right);
    console.log(root.val);
};

截屏2023-12-25下午4.13.03.png