# Ruby's Louvre

## leetcode 141 判定链表是否有环

   function isLinkedListContainsLoop( head){
return false;
}
while(slowPtr.next!=null && fastPtr.next.next!=null){
slowPtr=slowPtr.next;
fastPtr=fastPtr.next.next;
if(slowPtr==fastPtr){
return true;
}
}
return false;
}


## LeetCode 142 找出环的入口点（起点）

function findLinkedListLoopBegin(head) {
return null;
}
while (slowPtr.next != null && fastPtr.next.next != null) {
slowPtr = slowPtr.next;
fastPtr = fastPtr.next.next;
if (slowPtr == fastPtr) {
break;
}
}
let count = 1
while (slowPtr == fastPtr) {
slowPtr = slowPtr.next;
fastPtr = fastPtr.next;
count++
}
return slowPtr;
}
return null;
}


S=（B-A）*n

function circularArrayLoop(nums) {
let n = nums.length;
if (n <= 1) {
return false
}
function getNext(i) {
return (i + nums[i] + n) % n
}

for (let i = 0; i < n; i++) {
let slow = i, fast = getNext(i);
//确保总是朝着一个方向前进
while (nums[slow] * nums[i] > 0 && nums[fast] * nums[i] > 0) {
if (slow == fast) {
//判断是否只有一个元素
if (slow == getNext(slow)) {
break;
}
return true;
}
slow = getNext(slow);
fast = getNext(fast);//快指针每次走两步
if (nums[fast] * nums[i] < 0) {//如果方向反了
break;
}
fast = getNext(fast);
}
}
return false;
}

console.log(circularArrayLoop([2, -1, 1, 2, 2]))
console.log(circularArrayLoop([-1, 2]))
console.log(circularArrayLoop([-2, 1, -1, -2, -2]))



posted on 2020-01-07 00:38  司徒正美  阅读(729)  评论(0编辑  收藏  举报