题目原文:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
题目大意:
判断一个单链表有没有环。如果有环,返回环的起点,没有环返回null
题目分析:
还是用HashSet存,第一个重复的节点就是环的起点。
源码:(language:java)
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
HashSet<ListNode> set = new HashSet<ListNode>();
for(ListNode node=head;node!=null;node=node.next) {
if(!set.add(node))
return node;
}
return null;
}
}
成绩:
12ms,beats 5.82%,众数1ms,81.12%