0
点赞
收藏
分享

微信扫一扫

数据结构与算法之LeetCode-142-环形链表II(使用哈希和双指针求解)

witmy 2022-03-22 阅读 57

142. 环形链表 II - 力扣(LeetCode) (leetcode-cn.com)

哈希表

保存遍历结果,如果出现相同的则返回

var detectCycle = function(head){
  const visited = new Set();
  while(head!==null){
    if(visited.has(head)){
      return head;
    }
    visited.add(head);
    head = head.next;
  }
  return null;
};
快慢指针

快指针移动两个位置,慢指针只移动一个位置

var detectCycle = function(head){
  if(head === null){
    return null
  }
  let slow = head, fast = head;
  
  while(fast!==null){
    slow = slow.next;
    
    if(fast.next!==null){
      fast = fast.next.next;
    }else{
      return null; 
  	}
    
    if(fast === slow){
      let ptr = head;
      while(ptr!==slow){
        ptr = ptr.next;
        slow = slow.next;
      }
      return ptr;
    }
  }
  return null;
}

参考链接

142. 环形链表 II - 力扣(LeetCode) (leetcode-cn.com)

环形链表 II - 环形链表 II - 力扣(LeetCode) (leetcode-cn.com)

举报

相关推荐

0 条评论