一、链表是否有环
var hasCycle = function(head) { let fast, slow; fast = slow = head while(fast !== null && fast.next !== null) { fast = fast.next.next slow = slow.next if(fast === slow) { return true } } return false}
二、环的起点
var detectCycle = function(head) { let fast, slow; fast = slow = head while(fast !== null && fast.next !== null) { fast = fast.next.next slow = slow.next if(fast === slow) break; } if(fast === null || fast.next === null) { return null } slow = head while(slow !== fast) { fast = fast.next slow = slow.next } return slow}
三、链表中间节点
var middleNode = function(head) { let fast, slow; fast = slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } // slow 就在中间位置 return slow;};
四、链表倒数第K个元素
var getKthFromEnd = function(head, k) { let slow, fast; slow = fast = head; while (k-- > 0) fast = fast.next; while (fast != null) { slow = slow.next; fast = fast.next; } return slow;};
五、二分查找
var search = function(nums, target) { if (nums.length === 0) return -1; let left = 0, right = nums.length - 1; while (left <= right) { let mid = Math.floor(left + (right - left) / 2); if (nums[mid] < target) { left = mid + 1; } else if (nums[mid] > target) { right = mid - 1; } else if (nums[mid] === target) { // 直接返回 return mid; } } // 直接返回 return -1;};
六、两数之和
var twoSum = function(nums, target) { let left = 0, right = nums.length - 1; while (left < right) { let sum = nums[left] + nums[right]; if (sum === target) { // 题目要求的索引是从 1 开始的 return [left + 1, right + 1]; } else if (sum < target) { left++; // 让 sum 大一点 } else if (sum > target) { right--; // 让 sum 小一点 } } return [-1, -1];};
七、反转数组
var reverseString = function(s) { let left = 0; let right = s.length - 1; while (left < right) { // swap(s[left], s[right]) let temp = s[left]; s[left] = s[right]; s[right] = temp; left++; right--; }};