Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Can you solve it without using extra space?
Algorithm:
The classic fast & slow pointer problem
The classic fast & slow pointer problem
Just like the clock has 3 hands with different speed.
If there's a cycle, they will meet eventually.
Solutions:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public boolean hasCycle(ListNode head) { ListNode slow = head, fast = head; while (fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; if (slow == fast) return true; } return false; } }
Performance:
More intuitively, is to save each node reference in a HashSet (Sorted unique elements hash table).
Return true if found a duplicate. But this method takes more time(Around 10 ms) and need extra space.
Solution 2:
public class Solution { public boolean hasCycle(ListNode head) { Set<ListNode> mySet = new HashSet<ListNode>(); while(head != null){ if(mySet.contains(head)){ return true; } else{ mySet.add(head); head = head.next; } } return false; } }
No comments:
Post a Comment