两种思路
第一 : 想到判读重复问题,hash表是很好的结构,可以使用hashSet存储元素,可以判断是否出现过,
空间复杂度O(n),时间复杂度O(n)
第二 : 双指针,追及问题,一个快一个慢,若存在环,快的指针必定会追上慢的指针
空间复杂度O(n),时间复杂度O(1)
/**
* 利用哈希表的特性。
* tips: 哈希表是判断重复或者存储一个后面需要用到的数据的重要方法
* @param head
* @return
*/
public static boolean solution(ListNode head) {
HashSet<ListNode> set = new HashSet<>();
while (head != null){
if (set.contains(head)){
return true;
}else {
set.add(head);
head = head.next;
}
}
return false;
}
/**
* 双指针
* 快慢指针
*/
public static boolean solution2(ListNode head){
if (head == null || head.next ==null){
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast != slow){
if (fast == null || fast.next == null){
return false;
}
fast = fast.next.next;
slow = slow.next;
}
return true;
}