leetcode吧 关注:1,123贴子:2,456
  • 6回复贴,共1

141 Linked List Cycle 非常tricky的感觉。 觉得越刷越迷失

只看楼主收藏回复

判断链表 LinkList 是否带循环。
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

我看到就蒙了 感觉我工作上头基本没有用过linklist这种数据结构。 都是List 或者Dictionary 或者array
那么这个LinkList如果是一个类的话 类的实例(引用类型)可以直接比较吗?我就写了如下的solution 虽然accepted了 但是 faster than
0.86% 感觉这题还得重做。我也看了别人的算法 感觉自己都快不会写代码了。
public bool HasCycle(ListNode head) {
if(head==null) return false;
List<ListNode> nodes=new List<ListNode>();
while(head.next!=null){
if(nodes.Contains(head)){return true;}
else{
nodes.Add(head);
head=head.next;
}
}
return false;
}


IP属地:上海1楼2018-12-18 17:26回复
    你这个算法改进的话 把list改成hashmap,会快很多。这道题的最佳算法是数学题,可以不用额外空间。


    来自iPhone客户端2楼2018-12-19 01:51
    回复(2)
      2025-08-25 08:22:44
      广告
      不感兴趣
      开通SVIP免广告
      关于 散列表 HashTable HashSet
      参考算法图解。
      复习 为什么它们可以查找这么快 如果数组没有排序O(n) 排序O(logn) 而散列表 只是O(1) 为什么呢 因为它用到一个散列函数。把搜索作为参数传入,输入都是不同的 直接给出 存储的位置。
      笔记: 散列函数总是将统一的输入映射到相同的索引。
      散列函数将不同的输入映射到不同的索引。 映射到数组的不同位置。
      散列函数知道数组有多大,只返回有效的索引。
      数组和链表都被直接映射到内存,但散列表更复杂,它使用散列函数来确定元素的存储位置。
      改进为
      public bool HasCycle(ListNode head) {
      if(head==null) return false;
      HashSet<ListNode> nodes=new HashSet<ListNode>();
      while(head.next!=null){
      if(nodes.Contains(head)){return true;}
      else{
      nodes.Add(head);
      head=head.next;
      }
      }
      return false;
      }
      Runtime: 112 ms, faster than 78.62% of C# online submissions for Linked List Cycle.
      O(∩_∩)O 这下记住散列函数了。


      IP属地:上海3楼2018-12-20 16:11
      回复
        老哥你的刷题顺序是什么


        IP属地:江苏来自iPhone客户端4楼2018-12-30 10:04
        回复(1)