返回

JS手写实现:不可忽视的面试重点

前端

在前端面试中,JS手写实现能力是不可忽视的考察重点。本文将对JS手写实现的相关算法进行梳理,并提供具体的代码示例,助力你提升面试表现。

算法类型

JS手写实现涉及的算法类型主要包括以下几种:

  • 排序算法: 冒泡排序、快速排序、归并排序等
  • 搜索算法: 线性搜索、二分查找等
  • 数据结构: 栈、队列、链表等
  • 动态规划: 斐波那契数列、最长公共子序列等
  • 贪心算法: 活动选择问题、哈夫曼编码等

具体实现

以下是一些常见的JS手写实现算法:

  • 冒泡排序:
const bubbleSort = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  return arr;
};
  • 快速排序:
const quickSort = (arr, left, right) => {
  if (left < right) {
    const pivotIndex = partition(arr, left, right);
    quickSort(arr, left, pivotIndex - 1);
    quickSort(arr, pivotIndex + 1, right);
  }
};

const partition = (arr, left, right) => {
  const pivot = arr[right];
  let i = left - 1;
  for (let j = left; j < right; j++) {
    if (arr[j] < pivot) {
      i++;
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
  }
  [arr[i + 1], arr[right]] = [arr[right], arr[i + 1]];
  return i + 1;
};
  • 链表:
class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  add(value) {
    const newNode = new Node(value);
    if (!this.head) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;
      this.tail = newNode;
    }
  }

  remove(value) {
    if (!this.head) {
      return;
    }
    if (this.head.value === value) {
      this.head = this.head.next;
      if (!this.head) {
        this.tail = null;
      }
      return;
    }
    let current = this.head;
    while (current.next) {
      if (current.next.value === value) {
        current.next = current.next.next;
        if (!current.next) {
          this.tail = current;
        }
        return;
      }
      current = current.next;
    }
  }
}

注意事项

在JS手写实现中,需要注意以下事项:

  • 确保代码的正确性,避免逻辑错误。
  • 注意时间复杂度和空间复杂度,选择合适的算法。
  • 遵循代码规范,保持代码的可读性和可维护性。
  • 练习手写代码,熟练掌握算法的实现过程。

结论

JS手写实现是前端面试中的必备技能,掌握常见的算法和具体的代码示例至关重要。通过练习和理解,你可以提升自己的面试表现,为前端开发之路打下坚实的基础。