141 Linked List Cycle 非常tricky的感觉。 觉得越刷越迷失
leetcode吧
全部回复
仅看楼主
level 6
milk_bread 楼主
判断链表 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;
}
2018年12月18日 09点12分 1
level 6
milk_bread 楼主
关于 散列表 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 这下记住散列函数了。
2018年12月20日 08点12分 3
1