位运算相关

判断奇数偶数

&以特定的方式组合操作二进制数中对应的位,如果对应的位都为1,那么结果就是1, 如果任意一个位是0 则结果就是0。

  1. // 0的二进制表示为: 00000000 00000000 00000000 00000000
  2. // 1的二进制表示为: 00000000 00000000 00000000 00000001
  3. // 2的二进制表示为: 00000000 00000000 00000000 00000010
  4. // 3的二进制表示为: 00000000 00000000 00000000 00000011
  5. // 4的二进制表示为: 00000000 00000000 00000000 00000100
  6. funciton isOdd(n) {
  7. return n & 1 === 1;
  8. }

二分查找

  1. // 非递归版本
  2. function binarySearch(nums, target) {
  3. let low = 0;
  4. let high = nums.length - 1;
  5. while(low <= high) {
  6. let mid = parseInt((low + high) / 2);
  7. if(nums[mid] === target) {
  8. return mid;
  9. }
  10. if(nums[mid] > target) {
  11. high = mid - 1;
  12. }
  13. if(nums[mid] < target) {
  14. low = mid + 1;
  15. }
  16. }
  17. return -1;
  18. }
  19. // 递归
  20. function binarySearch(nums, target) {
  21. let low = 0;
  22. let high = nums.length -1;
  23. const binaryWalker = (nums, low, high, target) => {
  24. if(low > high) return -1;
  25. const mid = parseInt((low + high) / 2);
  26. if(nums[mid] === target) return mid;
  27. if(nums[mid] > target) return binaryWalker(nums, low, mid - 1, target);
  28. if(nums[mid] < target) return binaryWalker(nums, low + 1, high, target);
  29. }
  30. return binaryWalker(nums, low, high, target);
  31. }

常见排序

冒泡

  1. function bubbleSort(arr) {
  2. let i = arr.length - 1;
  3. while(i >= 0) {
  4. for(let j = 0; j < i; j++) {
  5. if(arr[j] > arr[j + 1]) {
  6. [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
  7. }
  8. }
  9. i--;
  10. }
  11. return arr;
  12. }

快排

  1. function quickSort(arr) {
  2. if(arr.length <= 1) return arr;
  3. let left = [];
  4. let right = [];
  5. let pivot = arr[0];
  6. for(let i = 1; i < arr.length; i++) {
  7. if(arr[i] >= pivot) {
  8. right.push(arr[i]);
  9. } else {
  10. left.push(arr[i]);
  11. }
  12. }
  13. return [...quickSort(left), pivot, ...quickSort(right)];
  14. }

二叉树遍历相关

先序遍历(中->左->右)

  1. // 递归实现
  2. function preOrderTraverse(root) {
  3. if(root) {
  4. console.log(root);
  5. preOrderTraverse(root.left);
  6. preOrderTraverse(root.right);
  7. }
  8. }
  9. // 非递归实现
  10. function preOrderTraverse(root) {
  11. let stack = [];
  12. if(root) {
  13. stack.push(root);
  14. }
  15. while(stack.length) {
  16. let temp = stack.pop();
  17. console.log(temp);
  18. if(temp.right) stack.push(temp.right);
  19. if(temp.left) stack.pus(temp.left);
  20. }
  21. }

层次遍历

  1. function levelTraverse(root) {
  2. if(!root) return;
  3. let stack = [];
  4. stack.push(root);
  5. while(stack.length) {
  6. let temp = stack.shift();
  7. console.log(temp);
  8. if(temp.left) stack.push(temp.left);
  9. if(temp.right) stack.push(temp.right);
  10. }
  11. }