手写算法: 移除元素

27. 移除元素open in new window

思路

  1. 可以用双指针, 两个指针初始时分别位于数组的首尾,向中间移动遍历该序列;

  2. 如果左指针指向的元素等于 val,此时将右指针指向的元素赋值给左指针,右指针左移,直至左指针指的元素不等于 val;

  3. 当左指针和右指针重合的时候,左右指针遍历完数组中所有的元素;

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
function removeElement(nums, val) {
  let left = 0,
    right = nums.length;

  while (left < right) {
    if (nums[left] === val) {
      nums[left] = nums[right - 1];
      right--;
    } else {
      left++;
    }
  }
  return left;
}

手写题:用 es5 实现 extends

53. 用 es5 实现extendsopen in new window

解法一:用 apply 改作用域

const myExtends = (SuperType, SubType) => {
  function Child(...args) {
    SuperType.apply(this, args);
    SubType.apply(this, args);
    this.__proto__ = SubType.prototype;
  }

  SubType.prototype.__proto__ = SuperType.prototype;
  Child.__proto__ = SuperType;

  return Child;
};

解法二:用 es5 自带的 Object.setPrototypeOf()

const myExtends = (SuperType, SubType) => {
  function Child(...args) {
    SuperType.apply(this, args);
    SubType.apply(this, args);
    Object.setPrototypeOf(this, SubType.prototype);
  }

  Object.setPrototypeOf(SubType.prototype, SuperType.prototype);
  Object.setPrototypeOf(Child, SuperType);

  return Child;
};
Last Updated:
Contributors: kk