Skip to content
On this page

深度搜索

typescript
// 节点构造函数
function Node(key) {
    this.children = [] //不确定当前节点子节点数,使用数组表示
    this.key = key //当前节点序号
}

// 创建节点
let n1 = new Node(1),
    n2 = new Node(2),
    n3 = new Node(3),
    n4 = new Node(4),
    n5 = new Node(5),
    n6 = new Node(6)

// 构建数
n1.children.push(n2, n5)
n2.children.push(n3, n4)
n5.children.push(n6)

// 深度优先搜索算法实现  先进后出
function dfs(node) {
    const stack = [node] // 模拟栈 先进后出
    while (stack.length > 0) {
        //栈中存在数据
        const first = stack.shift() // 从头部获取出栈元素
        console.log(first.key) // 打印出出栈元素序号
        first.children
            .slice()
            .reverse() // 先进后出 所以先进5
            .forEach(child => {
                stack.unshift(child) // 从头部插入进栈元素
                // stack.push(child)
            })
    }
}

dfs(n1) // 1,2,3,4,5,6

//利用递归实现dfs 递归就是一直优先执行第一个元素
function dfs2(node) {
    console.log(node.key)
    node.children.forEach(dfs2)
}

广度搜索

typescript
// 节点构造函数
function Node(key) {
    this.children = [] //不确定当前节点子节点数,使用数组表示
    this.key = key //当前节点序号
}

// 创建节点
let n1 = new Node(1),
    n2 = new Node(2),
    n3 = new Node(3),
    n4 = new Node(4),
    n5 = new Node(5),
    n6 = new Node(6)

// 构建数
n1.children.push(n2, n5)
n2.children.push(n3, n4)
n5.children.push(n6)
// 广度优先搜索算法实现 先进先出
function bfs(node) {
    const queue = [node] //创建一个队列
    while (queue.length) {
        //队列存在元素
        const first = queue.shift() //先出
        console.log(first.key) //出列元素序号
        first.children.forEach(
            child => queue.push(child) //子节点进入队列
        )
    }
}
bfs(n1) // 1,2,3,4,5,6

中序遍历

走完左边 再添加当前 再走右 后序遍历 走完左边 再走右 最后添加当前节点

递归与迭代

递归的调用就是基于栈结构,先进后出 迭代要模拟递归,其实就是模拟栈的先进后出

typescript
var preorderTraversal = function (root) {
    const res = []
    // 递归函数
    function _preorder(node) {
        if (!node) return
        res.push(node.val)
        _preorder(node.left)
        _preorder(node.right)
    }
    _preorder(root)
    return res
}

var preorderTraversal = function (root) {
    if (!root) return []
    const stack = [root]
    const res = []
    while (stack.length) {
        // 出栈
        const cur = stack.pop()
        res.push(cur.val)
        // 子节点存在压入栈中,先右再左
        cur.right && stack.push(cur.right)
        cur.left && stack.push(cur.left)
    }
    return res
}

打乱一个数组

javascript
// 打乱一个数组
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.sort(() => {
    return Math.round(Math.random()) - 0.5; //返回随机值(大于0|小于0)
})
console.log(arr);

后缀获取

javascript
// 获取后缀
function getType(path) {
    var index1 = path.lastIndexOf(".");
    var index2 = path.length;
    var type = path.substring(index1 + 1, index2);
    return type;
}
console.log(getType('/tmp/test.js'))

function getType(path) {
    var index1 = path.lastIndexOf(".");
    var index3 = path.lastIndexOf("/");
    if (index3 > index1) {
        return null
    }
    // console.log(index1,index3)
    var index2 = path.length;
    var type = path.substring(index1 + 1, index2);
    return type;
}
console.log(getType('/test.abc/file'))

回文检测

javascript
// 回文检测1
function fn(str) {
    var ostr = '';
    // 倒转字符串
    for (var i = str.length - 1; i >= 0; i--) {
        ostr += str[i];
    }
    //console.log(str,str1);
    if (ostr === str) {
        console.log('是回文');
    } else {
        console.log('不是回文');
    }
}
fn('abcba');
// 回文检测2
function fn(str) {
    for (var i = 0; i < str.length / 2; i++) {
        if (str[i] !== str[str.length - 1 - i]) {
            return '不是回文';
        } else if (i === parseInt(str.length / 2) - 1) {
            return '是回文';
        }
    }
}
console.log(fn('12345654321'));

获取url参数

javascript
// 解析url的参数为对象
var url = "www.baidu.com/index.php?name=aa&password=123"

function parseUrl(url) {
    var reg = new RegExp(/\?/)
    var index = reg.exec(url).index
    var query = url.substr(index + 1, url.length)
    var arr = query.split('&')
    var obj = {}
    arr.forEach(i => {
        var a = i.split('=')[0]
        var b = i.split('=')[1]
        obj[a] = b
        console.log(obj)
    });
    return obj
}
parseUrl(url)
// 方法二
var url = "http://item.taobao.com/item.htm?a=1&b=2&c=c&d=xxx"

function serilizeUrl(url) {
    var result = {};
    url = url.split("?")[1];
    console.log(url)
    var map = url.split("&");
    console.log(map)
    for (var i = 0, len = map.length; i < len; i++) {
        result[map[i].split("=")[0]] = map[i].split("=")[1];
    }
    return result;
}
serilizeUrl(url)

降维数组

javascript
// 降维数组
var arr = [
    [1, 2],
    [3, 4]
];

function Jw(obj) {
    return Array.prototype.concat.apply([], obj); // [ 1, 2, 3, 4 ]
    return [].concat(obj) // [ [ 1, 2 ], [ 3, 4 ] ]
}
console.log(Jw(arr))

排序

javascript
// 冒泡排序 从左边第一个数开始,把他和其他数一个个比较,最后放在合适位置
var array = [5, 4, 3, 2, 6, 1];
for (var i = 0; i < array.length; i++) {
    // console.log("i:" + i, array)
    // 判断一个,数组判断往后减一个
    for (var j = 0; j < array.length - i - 1; j++) {
        if (array[j] > array[j + 1]) {
            [array[j], array[j + 1]] = [array[j + 1], array[j]]
        }
        console.log('比较' + j, array)
    }
}

// var arr = new Array(10).fill('').map((_, index) => index + 1)
// console.log(arr)

// 冒泡排序
function bubbleSort(arr) {
    for (var i = 0; i < arr.length; i++) {
        for (var j = 0; j < arr.length - 1 - i; j++) {
            if (arr[j] < arr[j + 1]) {
                var big = arr[j + 1]
                arr[j + 1] = arr[j]
                arr[j] = big
            }
        }
    }
    return arr
}

// 其他排序
let arr = [1, 2, 4, 3, 5]
arr.sort((a, b) => {
    return a - b
})
console.log(arr)

数组扁平化 || 数组降维

javascript
// 数组扁平化 || 数组降维
let arr = [1, [1, 2], 3]
// 方法一
const flattenDeep = arr => Array.isArray(arr) ? arr.reduce((resArr, item) => [...resArr, ...flattenDeep(item)], []) : [arr]
console.log(flattenDeep(arr))
// 方法二
function paiping(arr) {
    return arr.reduce((resArr, item) => {
        return resArr.concat(Array.isArray(item) ? paiping(item) : item)
    }, [])
}
console.log(paiping(arr))

去前后空格

javascript
// 去前后空格
function trim(str) {
    if (typeof str === "string") {
        return str.replace(/(^\s*)|(\s*)$/g, ""); //去除前后空白符
    }
    return null
}
console.log(trim('  22  '))

三数之和为15的组合

javascript
// 算法:三数之和为15的组合
let array = [1, 2, 3, 4, 5, 6]
let n = 3
let sum = 12
let temp = []

function fn(array, n, sum, temp) {
    if (temp.length === 3) {
        if (temp.reduce((a, b) => a + b) === sum) {
            return temp
        }
        return false
    }
    for (let i = 0; i < array.length; i++) {
        // console.log(i)
        const current = array.shift()
        // console.log(array)
        temp.push(current) // temp=[0]
        // console.log(temp)
        // fn(array, n, sum, temp)
        let result = fn(array, n, sum, temp)
        if (result) {
            console.log(result)
            // return result
        }
        temp.pop()
        array.push(current)
    }
}
fn(array, n, sum, temp)

// 这个也可以达到相同效果
let array = [1, 2, 3, 4, 5, 6]
let n = 3
let sum = 12
let temp = []

function fn(array, n, sum, temp) {
    // 主要用来筛选长度
    if (temp.length === 3) {
        if (temp.reduce((a, b) => a + b) === sum) {
            return temp
        }
        return false
    }
    for (let i = 0; i < array.length; i++) {
        temp.push(array[i])
        // console.log(temp)
        let result = fn(array, n, sum, temp)
        if (result) {
            console.log(result)
            // return result
        }
        temp.pop()
    }
}
fn(array, n, sum, temp)

数组去重

javascript
// 数组去重  indexOf
function isDuplicate(arr) {
    let res = []
    for (let i in arr) {
        if (res.indexOf(arr[i]) == -1) {
            res.push(arr[i])
        }
    }
    return res
}
let arr = [1, 2, 3, 2, 3, 1, 4];
console.log(isDuplicate(arr));

//  reduce去重 元素为对象
var arr = [{
    key: '01',
    value: '王元宝'
}, {
    key: '02',
    value: '吴富贵'
}, {
    key: '01',
    value: '王宝'
}, {
    key: '04',
    value: '吴富贵'
}];
var obj = {};
arr = arr.reduce((newArr, next) => {
    // 找key,有则不理,没有添加输出
    obj[next.key] ? '' : obj[next.key] = true && newArr.push(next)
    return newArr
    // return console.log(newArr, next)
}, []);
console.log(arr)

// reduce 函数接收4个参数: arr.reduce((累计器,当前值,当前索引,源数组)=>{},[initialValue])
var arr = [1, 2, 3, 4];
var sum = arr.reduce((prev, cur, index, arr) => {
    return prev + cur;
})
console.log(arr, sum);

//  filter去重 --不改原数组
var arr = [5, 6, 8, 8, 6, 8, 6, 9];
var res = arr.filter((item, index, arry) => {
    // console.log(items, index)
    // 第一次找到的index是不是当前item的index,过滤掉不一样的
    return arry.indexOf(item) === index
});
console.log(arr, res) // [5, 6, 8]

// ES6 set去重
var arr = [5, 6, 8, 8, 6, 8, 6];
console.log(new Set(arr))
console.log([...new Set(arr)])
console.log(Array.from(new Set(arr)))

驼峰转下划线

javascript
let str = 'userName666'
// 大写字母或者数字
// - param 1: 匹配到的字符串
// - param 2: 匹配的子字符串
// - param 3: 匹配到的字符串在字符串中的位置
// - param 4: 原始字符串
console.log(str.replace(/([A-Z]|\d+)/g, (a, b, c, d) => {
    console.log(a, b, c, d)
    return `_${b.toLowerCase()}`
}))

判断一个字符串中出现次数最多的字符,统计这个次数

javascript
// 判断一个字符串中出现次数最多的字符,统计这个次数
var str = 'asdfssaaasasasasaa';
var json = {};
for (var i = 0; i < str.length; i++) {
    if (!json[str.charAt(i)]) {
        json[str.charAt(i)] = 1;
    } else {
        json[str.charAt(i)]++;
    }
};
var iMax = 0;
var iIndex = '';
for (var i in json) {
    console.log(i)
    if (json[i] > iMax) {
        iMax = json[i];
        iIndex = i;
    }
}
console.log('出现次数最多的是:' + iIndex + '出现' + iMax + '')

// 统计字符串哪个字符串出现最多
function fn(str) {
    var obj = {}
    for (let i = 0; i < str.length; i++) {
        var char = str.charAt(i);
        if (obj[char]) {
            obj[char]++
        } else {
            obj[char] = 1
        }
    }
    // console.log(obj)
    var max = 0;
    var maxStr = null;
    for (key in obj) {
        if (obj[key] > max) {
            max = obj[key]
            maxStr = key
        }
    }
    console.log(maxStr + "出现最多,次数为:" + max)
}
var s = "afhalghasdhfldhglkasdhglhsal"
fn(s)

toArray

javascript
[].slice() === Array.prototype.slice(); // true
var arrayLike = {
    0: 'a',
    1: 'b',
    2: 'c',
    length: 3
}

function toArray(arrayLike) {
    return [].slice.call(arrayLike)
}
console.log(toArray(arrayLike))

粤ICP备2024285819号