常见的手写题

93 阅读1分钟
  1. 合并两个有序数组

    var merge = function (nums1, m, nums2, n) {
      nums1.length = m;
      const nums = [];
      let p = 0;
      let q = 0;
      let maxL = Math.max(m, n);
    
      while (p < m && q < n) {
        if (nums1[p] < nums2[q]) {
          nums.push(nums1[p]);
          p++;
        } else {
          nums.push(nums2[q]);
          q++;
        }
      }
    
      while (p < m) {
        nums.push(nums1[p]);
        p++;
      }
    
      while (q < n) {
        nums.push(nums2[q]);
        q++;
      }
    
      return nums1 = nums;
    };
    
  2. 最长回文字符串

    const a = 'cbbd';
    var longestPalindrome = function(s) {
      let res = ''; // 定义返回的最长回文子串
      for (let i = 0; i < s.length; i++) {
        match(i,i);
        match(i,i+1);
      }
    
      function match(m, n) {
        while( m >= 0 && n < s.length && s[m] === s[n]){
          m--;
          n++;
        }
        const t = s.slice(m+1,n);
        if (n-m-1 > res.length) {
          res = s.slice(m+1,n)
        }
      }
    
      return res;
    };
    
    const cc = longestPalindrome(a) 
    
  3. 检查死锁

    const checkDeadLock = (dependencies) => {
      const graph = new Map();
      for ([from,to] of dependencies) {
        if (!graph.has(from)) {
          graph.set(from, new Set());
        }
        graph.get(from).add(to);
      }
    
      const visited = new Set();
      const recStack = new Set();
    
      const isCyclic = (node) => {
        if (resStack.has(node)) {      return true;    }    if (visited.has(node)) {      return false;    }
        visited.add(node);
        recStack.add(node);
        console.log('visited',visited)
        console.log('recStack',recStack)
        if(graph.has(node)){
          for (const neighbor of graph.get(node)) {
            if (!visited.has(neighbor)) {
              if (isCyclic(neighbor)) {
                return true;
              }
            }
          }
        }
        recStack.delete(node);
        return false;
      }
    
      for(const [node] of graph) {
        if(!visited.has(node)) {
          if(isCyclic(node)) {
            return true;
          }
        }
      }
    
      return false;
    }
    
    // 测试代码
    const dependencies = [
      ['A', 'B'],
      ['A', 'C'],
      ['B', 'C'],
      ['B', 'D'],
      ['C', 'D'],
      ['D', 'A'],
    ];
    
    console.log(checkDeadLock(dependencies)); 
    
  4. 查找公共时间范围

    function getCommonSalePeriods(product1, product2) {
      let commonPeriods = [];
    
      for (let period1 of product1) {
        for (let period2 of product2) {
          let start1 = parseInt(period1[0], 10);
          let end1 = parseInt(period1[1], 10);
          let start2 = parseInt(period2[0], 10);
          let end2 = parseInt(period2[1], 10);
    
          let commonStart = Math.max(start1, start2);
          let commonEnd = Math.min(end1, end2);
    
          if (commonStart < commonEnd) {
            commonPeriods.push([commonStart.toString().padStart(4, '0'), commonEnd.toString().padStart(4, '0')]);
          }
        }
      }
    
      return commonPeriods;
    }
    
    let product1 = [['0720','0938'],['0812','0934']];
    let product2 = [['0730','0830'],['0900','1000']];
    console.log(getCommonSalePeriods(product1, product2));
    
  5. 防抖

    function debounce(fn, delay) {
      let timer;
      return function() {
        const ctx = this;
        const args = arguments;
        if(timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          fn.apply(ctx, args);
        },delay);
      }
    }
    
  6. 节流

    function throttle(fn, delay) {
      let lastTime = 0;
      return function() {
        const ctx = this;
        const args = arguments;
        const newTime = Date.now();
        if(newTime - lastTime > delay) {
          fn.apply(ctx, args);
          lastTime = newTime;
        }
      }
    }
    
  7. 手写Promise

    class Promise {
      constructor(executor) {
        this.promStatus = 'pending';
        this.promResult = undefined;
    
        const resolve = (val) => {
          if (this.promStatus !== 'pending') {
            return;
          }
          this.promStatus = 'fulfilled';
          this.promResult = val;
        }
    
        const reject = (err) => {
          if (this.promStatus !== 'pending') {
            return;
          }
          this.promStatus = 'rejected';
          this.promResult = err;
        }
    
        const then = (onFulfilled, onRejected) => {
          return new Promise((resolve, reject) => {
            const handleCb = (cb) => {
              try {
                const res = cb(this.promResult);
                if (res instanceof Promise) {
                  res.then((val) => resolve(val), err => reject(err))
                } else {
                  resolve(res)
                }
              } catch (error) {
                reject(error)
              }
            }
    
            if (this.promStatus === 'fulfilled') {
              handleCb(onFulfilled);
            }
            if (this.promStatus === 'rejected') {
              handleCb(onRejected);
            }
          })
        }
    
        try {
          executor(resolve, reject);
        } catch(e) {
          reject(err);
        }
      }
    }
    
  8. 深拷贝

    function deepClone(obj) {
      if(typeof obj !== 'object') return obj;
      let newObj = obj.isArray() ? [] : {};
      for (prop in obj) {
        if(obj.hasOwnProperty(prop)) {
          newObj[prop] = typeof prop === 'object' ? deepClone(prop) : obj[prop];
        }
      }
      return newObj;
    }