NodeJS实现哈希查找算法

 NodeJS实现哈希查找算法

以下是一个简单的Node.js示例,实现了哈希查找算法:

// 哈希查找函数
function hashSearch(array, target) {
    // 创建一个Map用于存储数组元素及其对应的索引
    const map = new Map();

    // 遍历数组,将元素及其索引放入Map中
    for (let i = 0; i < array.length; i++) {
        map.set(array[i], i);
    }

    // 查找目标值是否在Map中存在
    if (map.has(target)) {
        // 如果存在,返回目标值在数组中的索引
        return map.get(target);
    } else {
        // 如果不存在,返回-1表示未找到
        return -1;
    }
}

const array = [4, 7, 2, 9, 1, 5, 8, 3, 6];
const target = 5;
const index = hashSearch(array, target);

if (index !== -1) {
    console.log(`目标值 ${target} 在数组中的索引为: ${index}`);
} else {
    console.log(`未找到目标值 ${target}`);
}

在这个示例中,我们使用了Map来实现哈希查找算法。首先,我们遍历数组,将数组元素作为键,元素在数组中的索引作为值,存储在Map中。然后,我们可以通过目标值在Map中查找其索引,如果存在则返回索引,否则返回-1表示未找到。

 NodeJS实现哈希查找算法

以下是一个简单的Node.js示例,实现了哈希查找算法:

// 哈希查找函数
function hashSearch(array, target) {
    // 创建一个Map用于存储数组元素及其对应的索引
    const map = new Map();

    // 遍历数组,将元素及其索引放入Map中
    for (let i = 0; i < array.length; i++) {
        map.set(array[i], i);
    }

    // 查找目标值是否在Map中存在
    if (map.has(target)) {
        // 如果存在,返回目标值在数组中的索引
        return map.get(target);
    } else {
        // 如果不存在,返回-1表示未找到
        return -1;
    }
}

const array = [4, 7, 2, 9, 1, 5, 8, 3, 6];
const target = 5;
const index = hashSearch(array, target);

if (index !== -1) {
    console.log(`目标值 ${target} 在数组中的索引为: ${index}`);
} else {
    console.log(`未找到目标值 ${target}`);
}

在这个示例中,我们使用了Map来实现哈希查找算法。首先,我们遍历数组,将数组元素作为键,元素在数组中的索引作为值,存储在Map中。然后,我们可以通过目标值在Map中查找其索引,如果存在则返回索引,否则返回-1表示未找到。

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在