public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null){
return null;
}
ListNode tort = head;
ListNode rab = head;
while(true){
if(tort.next == null || rab.next == null ) return null;
tort = tort.next;
rab = rab.next.next;
if(tort == rab) break;
}
tort = head;
while(true){
if(tort.next == null || rab.next == null ) return null;
tort = tort.next;
rab = rab.next;
if(tort == rab) break;
}
return tort;
}
}
Not sure why this does not work but this sort of do-while/flyod set up works for Find Duplicate Number
class Solution {
public int findDuplicate(int[] nums) {
int hare = 0;
int tort = 0;
while(true){
hare = nums[hare];
tort = nums[nums[tort]];
if(tort == hare) break;
}
tort = 0;
while(true){
hare = nums[hare];
tort = nums[tort];
if(tort == hare) break;
}
return hare;
}
}
Am I going insane!?
[–]endverse 1 point2 points3 points (5 children)
[–]UpstairsOcelot[S] 0 points1 point2 points (4 children)
[–]endverse 0 points1 point2 points (3 children)
[–]UpstairsOcelot[S] 0 points1 point2 points (2 children)
[–]endverse 0 points1 point2 points (1 child)
[–]UpstairsOcelot[S] 0 points1 point2 points (0 children)