思路:使用两个指针,一个每次走一步,一个每次走两步,当两者相等时肯定存在环,并且如果存在环两者必有相等的时候。
存在环的可以一直走到两者相等,不存在环的会结束==null。
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode one=head;
ListNode two=head;
while(one!=null && two!=null){
one=one.next;
if(two.next!=null){
two=two.next.next;
if(one==two)
return true;
}else
return false;
}
return false;
}
}
思路:就是第二次相遇时必然时起点。
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head==null || head.next==null)
return null;
ListNode zero=head;
ListNode one=head;
ListNode two=head;
while(one!=null && two!=null){
one=one.next;
if(two.next!=null){
two=two.next.next;
if(two==zero)
return zero;
else if(two==one){
one=zero.next;
two=zero.next;
zero=zero.next;
}
}else{
return null;
}
}
return null;
}
}
287. Find the Duplicate Number
class Solution {
public int findDuplicate(int[] nums) {
int slow=nums[0];
int fast=nums[slow];
while(slow!=fast){
slow=nums[slow];
fast=nums[nums[fast]];
}
fast=0;
while(fast!=slow){
slow=nums[slow];
fast=nums[fast];
}
return slow;
}
}