面试题汇总(25)

64 阅读1分钟

1. 将一个数组旋转 k 步

  • 输入一个数组 [1,2,3,4,5,6,7]
  • k = 3, 即旋转 3 步
  • 输出 [5,6,7,1,2,3,4]
function rotate(arr, k) {
  const step = k % arr.length;
  const part1 = arr.slice(-step);
  const part2 = arr.slice(0, arr.length - step);
  return [...part1, ...part2];
}

2. 快速排序

  • 用 js 实现快速排序算法,并说明时间复杂度
function quickSort(arr) {
  if (arr.length <= 1) {
    return arr;
  }
  const pivotIndex = Math.floor(arr.length / 2);
  const pivot = arr.splice(pivotIndex, 1)[0];
  const left = [];
  const right = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < pivot) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }
  return quickSort(left).concat([pivot], quickSort(right));
}

3. 判断字符串是否是括号匹配的

  • 一个字符串中可能包含 [] () {} 三种括号
  • 判断该字符串是否是括号匹配的
  • (a{b}c)匹配,而{a(b{a(b)c)不匹配
function isMatch(str) {
  if (!str) return true;
  const leftStack = [];
  const length = str.length;
  const leftSymbols = "{[(";
  const rightSymbols = "}])";
  for (let i = 0; i < length; i++) {
    const s = str[i];
    if (leftSymbols.includes(s)) {
      leftStack.push(s);
    } else if (rightSymbols.includes(s)) {
      const top = leftStack[leftStack.length - 1];
      if (isMatch(left, right)) {
        leftStack.pop();
      } else {
        return false;
      }
    }
  }
  return leftStack.length === 0;
}

4. 反转单向链表

  • 输入一个单向链表,输出反转后的链表
  • 如输入1 -> 2 -> 3 -> 4 -> 5,输出5 -> 4 -> 3 -> 2 -> 1