leetcode 3217. 从链表中移除在数组中存在的节点

  • 3217. 从链表中移除在数组中存在的节点

题目

给你一个整数数组 nums 和一个链表的头节点 head。从链表中移除所有存在于 nums 中的节点后,返回修改后的链表的头节点。
示例 1:
输入: nums = [1,2,3], head = [1,2,3,4,5]
输出: [4,5]
解释:
移除数值为 1, 2 和 3 的节点。

题解

  • 超时问题,降低时间复杂度,采用hash
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {number[]} nums
 * @param {ListNode} head
 * @return {ListNode}
 */
var modifiedList = function (nums, head) {
    let newList = new ListNode(0, head);
    const set = new Set(nums);
    let cur = newList;
    while (cur.next) {
        if (set.has(cur.next.val)) {//哈希 O(1)
        // if (nums.includes(cur.next.val)) {//使用includes避免超时 O(n)
            cur.next = cur.next.next
        } else {
             cur = cur.next;
        }
    }
    return newList.next;
};

includes 和 set 速度对比

  • includes: includes 是数组的方法,它会对数组进行线性搜索,也就是从数组的第一个元素开始,逐个检查元素是否与目标元素相等,直到找到匹配元素或者遍历完整个数组。

  • set: Set 是一种无序且唯一的数据结构,它基于哈希表(Hash Table)实现。当调用 has 方法时,会根据元素的哈希值直接定位到对应的存储位置,从而快速判断元素是否存在。

  • 示例结果:10次去掉最高和最低的结果 取剩余的平均值
    >includes: 0.061ms
    set.has: 0.003ms
    includes 结果: true
    set.has 结果: true

    // 创建一个包含大量元素的数组
    const array = [];
    for (let i = 0; i < 100000; i++) {
      array.push(i);
    }
    
    // 创建一个包含相同元素的 Set
    const set = new Set(array);
    
    // 要查找的元素
    const target = 99999;
    
    // 测试 includes 方法的性能
    console.time("includes");
    const result1 = array.includes(target); //时间复杂度是O(n)
    console.timeEnd("includes");
    
    // 测试 set.has 方法的性能
    console.time("set.has");
    const result2 = set.has(target); //时间复杂度是O(1),
    console.timeEnd("set.has");
    
    console.log("includes 结果:", result1);
    console.log("set.has 结果:", result2);
    

你可能感兴趣的:(#,LeetCode刷题,leetcode,链表,算法)