54. 螺旋矩阵

  • 日期:2021/3/15
  • 难度:中等
  • 思路:给一个m行n列矩阵,按照顺时针返回所有元素。
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  let size = matrix.length * matrix[0].length;
  let res = [];
  let l = 0,
    r = matrix[0].length - 1,
    t = 0,
    b = matrix.length - 1;
  while (res.length < size) {
    for (let i = l; i <= r; i++) {
      res.push(matrix[t][i]);
    }
    t++;
    for (let i = t; i <= b; i++) {
      res.push(matrix[i][r]);
    }
    r--;
    // 判断纵向是否越界
    if (t > b) {
      break;
    }
    for (let i = r; i >= l; i--) {
      res.push(matrix[b][i]);
    }
    b--;
    // 判断横向是否越界
    if (l > r) {
      break;
    }
    for (let i = b; i >= t; i--) {
      res.push(matrix[i][l]);
    }
    l++;
  }
  return res;
};

59. 螺旋矩阵 II

  • 日期:2021/3/16
  • 难度:中等
  • 思路:给一个正整数n,生成n×n的矩阵,且元素按照逆时针排序。
/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function (n) {
  let cnt = 0,
    size = n * n;
  let res = new Array();
  for (let i = 0; i < n; i++) {
    res[i] = new Array();
  }
  let l = 0,
    r = n - 1,
    t = 0,
    b = n - 1;
  while (cnt < size) {
    for (let i = l; i <= r; i++) {
      res[t][i] = ++cnt;
    }
    t++;
    for (let i = t; i <= b; i++) {
      res[i][r] = ++cnt;
    }
    r--;
    for (let i = r; i >= l; i--) {
      res[b][i] = ++cnt;
    }
    b--;
    for (let i = b; i >= t; i--) {
      res[i][l] = ++cnt;
    }
    l++;
  }
  return res;
};

1603. 设计停车系统

  • 日期:2021/3/19
  • 难度:简单
  • 思路:建立一个数组,包含三种停车位的数量,进来就空位减一。
/**
 * @param {number} big
 * @param {number} medium
 * @param {number} small
 */
var ParkingSystem = function (big, medium, small) {
  this.arr = [big, medium, small];
};

/**
 * @param {number} carType
 * @return {boolean}
 */
ParkingSystem.prototype.addCar = function (carType) {
  if (this.arr[carType - 1] > 0) {
    this.arr[carType - 1]--;
    return true;
  }
  return false;
};

/**
 * Your ParkingSystem object will be instantiated and called as such:
 * var obj = new ParkingSystem(big, medium, small)
 * var param_1 = obj.addCar(carType)
 */

Q.E.D.


我还有很多想要完成的梦想。