基础面试算法笔记

大厂面试题:

---- https://www.cnblogs.com/hanxuming/p/10642074.html https://www.cnblogs.com/sexintercourse/p/12418512.html https://juejin.im/post/6864398060702760968

vue基本原理:自己解决下哈

  1. 求字符串中 最长无重复字符串长度(求长度和不重复字符串)
  2. 数组去重办法(两层for、filter、indexOf+for) 以后有机会重点看下filter,没明白
  3. DFS深度遍历多层级children,堆栈实现(也可以用递归,堆栈更优秀)
  4. 求和,使用reduce
  5. 手写简单深拷贝。(对象和数组等基础字段有效)
  6. 手写call
  7. 手写new
  8. 最长回文子串js


//第一题答案: 求字符串中 最长无重复字符串的长度 start
 // slice-》截取字符串
<span id="title1"></span>
        // Math.max.apply(this, itemNum)调用Math的max方法‘继承’
        const str = 'hello world'
        function getSum(arr) {
            let item = []
            let itemNum = []
            let len = arr.length
            let num = 0
            if (!len) {
                return []
            }
            for (let i = 0; i <= len; i++) {
                if (arr[i] != arr[i + 1]) {
                    num++
                } else {
                    item.push(arr.slice((i - num), i))
                    itemNum.push(num)
                    num = 0
                }
            }
            let getItem = function () {
                return item
            }
            let getItemNum = function () {
                return Math.max.apply(this, itemNum)
            }
            return {
                item: getItem(),
                itemNum: getItemNum()
            }
        }
        const getData = getSum(str)
        const getItem = getData.item
        const getItemNum = getData.itemNum
        console.log(getItem) // ["he", "lo world"]
        console.log(getItemNum) // 8
        // 求字符串中 最长无重复字符串的长度 end

// 第二题答案:数组去重,计算各方法消耗时间 start
<span id="title2"></span>
        // 普通es5两层嵌套的方法,注意第二场i+1开始
        // 数组去重办法
        // 普通es5两层嵌套的方法,注意第二场i+1开始
        let sliceHaveArr = arr => {
            let item = []
            const lengths = arr.length
            for (let i = 0; i < lengths; i++) {
                for (let y = i+1; y < lengths; y++) {
                    console.log(i,y)
                    if (arr[i] == arr[y]) {
                        arr.splice(y, 1)
                    }
                }
            }
            console.log(11,item)
            return arr
        }
        console.time(1)
        sliceHaveArr([1, 2, 4, 2, 6])
        console.timeEnd(1)
        //filter结合对象检索键名是否存在的hasOwnProperty方法
        let spliceRepeat = arr => {
            let getArr = {}
            return arr.filter(item => {
                return getArr.hasOwnProperty(typeof item + item) ? false : (getArr[typeof item + item] = true)
            })
        }
        console.time(1) //统计方法消耗时间 start
        spliceRepeat([1, 2, 3, 4, 5, 5, 3, 6])
        console.timeEnd(1) //统计方法消耗时间 end
        // indexOf方法
        function indexOfUnique(arr) {
            let item = []
            let len = arr.length
            if (len < 1) {
                return []
            }
            for (let i = 0; i < len; i++) {
                if (item.indexOf(arr[i]) < 0) {
                    item.push(arr[i])
                }
            }
            return item
        }
        console.log("indexOfUnique", indexOfUnique([1, 2, 3, 4, 5, 5, 5, 5, 3, 6]))
        // 数组去重,计算各方法消耗时间 end
        最简单,一句话
        const arr = [1, 2, 3, 3, 5, 6, 5]
        const a = new Set([...arr])
        console.log(a)

//第三题答案: 深度遍历DFS,没有使用递归,排除了内存溢出的风险start
const tree = {
    name: 'root',
    children: [
        {
            name: 'c1',
            children: [
                {
                    name: 'c11',
                    children: []
                },
                {
                    name: 'c12',
                    children: []
                }
            ]
        },
        {
            name: 'c2',
            children: [
                {
                    name: 'c21',
                    children: []
                },
                {
                    name: 'c22',
                    children: []
                }
            ]
        }
    ]
}
function solve(root) {
    let stack = [], result = []
    if (!root) {
        return []
    }
    stack.push(root)
    while (stack.length) {
        let node = stack.pop()
        if (node == null) {
            continue
        }
        result.push(node.name)
        for (let i = node.children.length - 1; i >= 0; i--) {
            // 这里是重点,应该从后面的节点压入栈中
            stack.push(node.children[i])
        }
    }
    return result
}
console.log(solve(tree))
// 深度遍历DFS end

// 第四题答案:求和 start
        var numbers = [1, 2, 3]
        // function getSum(total, num) {
        //     return total + num
        // }
        function myFun(item) {
            return numbers.reduce((total, num) => {
                return total + num
            })
        }
        console.log(myFun())
        // 求和 end

// 第五题答案1:手写简单深拷贝。这方案常用,比较稳妥,还没遇到问题
objb = JSON.parse(JSON.stringify(obja)))

// 第五题答案2:手写简单深拷贝,类型没有覆盖全面,比如日期格式无法拷贝
const obj = {
    arr: [1, 1],
    obj: { key: 11 },
    objKid: {
        name: '测试',
        child: {
            name: '测试child'
        }
    },
    a: () => { },
    date: new Date(),
    reg: /reg/g,
    null: null,
    undefined: undefined
}
function isObjFun(obj) {
    return (typeof obj === 'object' || typeof obj === 'function') && (obj !== null)
}
function clone(obj) {
    let newobj = Array.isArray(obj) ? [] : {}
    for (let i in obj) {
        newobj[i] = isObjFun(obj[i]) ? clone(obj[i]) : obj[i]
    }
    return newobj
}
const test = clone(obj)
obj.obj = 11
console.log(obj, test)

//第六题答案:手写call
Function.prototype.mycall = function (context, ...args) {
        context = Object(context) || window
        let fn = Symbol(1)
        context[fn] = this
        let result = context[fn](...args)
        delete context[fn]
        return result
    }
    function SuperObj(name = 'ted') {
        this.name = name
    }
    function SubObj(name) {
        this.age = 14
        console.log(111, this)
        SuperObj.mycall(this, name)
    }
    SubObj.prototype = new SuperObj()
    const a = new SubObj('xoao')
    console.log(a.name)

//第七题答案:手写new函数
function newTest (constructFunction){
  let obj = {};
  obj.__proto__ = constructFunction.prototype;
  return function(){
    constructFunction.apply(obj,arguments);
    return obj;
  }
}

//第八题答案:最长回文子串
const str = 'abba';
function getStr(val){
  if(val.length<1){ return 0 }
  let item = [];
  for(let i = 0; i < val.length; i++){
    for(let y = i+1; y <= val.length; y++){
      const due = val.slice(i,y);
      const turnOver = [...due].reverse().join('');
      if(due === turnOver){
        item.push(due)
      }
    }
  }
  const max = item.reduce((a,b) => {
    return a.length>b.length?a:b;
  })
  return max.length;
}
const palindrome = getStr(str);

posted @ 2021-06-18 16:18  问问大将军  阅读(26)  评论(0编辑  收藏  举报