版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85809041
Title: Linked List Cycle 141
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/linked-list-cycle/
1. 双指针
时间复杂度:O(n),一次一层while循环。
空间复杂度:O(1),没有申请额外空间。
/**
* 双指针
* @param head
* @return
*/
public static boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slower = head;
ListNode faster = head;
while (faster.next != null && faster.next.next != null) {
slower = slower.next;
faster = faster.next.next;
if (faster == slower) {
return true;
}
}
return false;
}
2. 集合Set唯一性
时间复杂度:O(n),一次一层while循环。
空间复杂度:O(n),申请额外空间集合Set。
/**
* 集合Set的唯一性
* @param head
* @return
*/
public static boolean hasCycle1(ListNode head) {
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (set.contains(head)) {
return true;
}
else {
set.add(head);
}
head = head.next;
}
return false;
}