一、链表是否有环

  1. var hasCycle = function(head) {
  2. let fast, slow;
  3. fast = slow = head
  4. while(fast !== null && fast.next !== null) {
  5. fast = fast.next.next
  6. slow = slow.next
  7. if(fast === slow) {
  8. return true
  9. }
  10. }
  11. return false
  12. }

二、环的起点

  1. var detectCycle = function(head) {
  2. let fast, slow;
  3. fast = slow = head
  4. while(fast !== null && fast.next !== null) {
  5. fast = fast.next.next
  6. slow = slow.next
  7. if(fast === slow) break;
  8. }
  9. if(fast === null || fast.next === null) {
  10. return null
  11. }
  12. slow = head
  13. while(slow !== fast) {
  14. fast = fast.next
  15. slow = slow.next
  16. }
  17. return slow
  18. }

三、链表中间节点

  1. var middleNode = function(head) {
  2. let fast, slow;
  3. fast = slow = head;
  4. while (fast != null && fast.next != null) {
  5. fast = fast.next.next;
  6. slow = slow.next;
  7. }
  8. // slow 就在中间位置
  9. return slow;
  10. };

四、链表倒数第K个元素

  1. var getKthFromEnd = function(head, k) {
  2. let slow, fast;
  3. slow = fast = head;
  4. while (k-- > 0)
  5. fast = fast.next;
  6. while (fast != null) {
  7. slow = slow.next;
  8. fast = fast.next;
  9. }
  10. return slow;
  11. };

五、二分查找

  1. var search = function(nums, target) {
  2. if (nums.length === 0) return -1;
  3. let left = 0, right = nums.length - 1;
  4. while (left <= right) {
  5. let mid = Math.floor(left + (right - left) / 2);
  6. if (nums[mid] < target) {
  7. left = mid + 1;
  8. } else if (nums[mid] > target) {
  9. right = mid - 1;
  10. } else if (nums[mid] === target) {
  11. // 直接返回
  12. return mid;
  13. }
  14. }
  15. // 直接返回
  16. return -1;
  17. };

六、两数之和

  1. var twoSum = function(nums, target) {
  2. let left = 0, right = nums.length - 1;
  3. while (left < right) {
  4. let sum = nums[left] + nums[right];
  5. if (sum === target) {
  6. // 题目要求的索引是从 1 开始的
  7. return [left + 1, right + 1];
  8. } else if (sum < target) {
  9. left++; // 让 sum 大一点
  10. } else if (sum > target) {
  11. right--; // 让 sum 小一点
  12. }
  13. }
  14. return [-1, -1];
  15. };

七、反转数组

  1. var reverseString = function(s) {
  2. let left = 0;
  3. let right = s.length - 1;
  4. while (left < right) {
  5. // swap(s[left], s[right])
  6. let temp = s[left];
  7. s[left] = s[right];
  8. s[right] = temp;
  9. left++; right--;
  10. }
  11. };