LeetCode算法学习总结- 中等

螺旋矩阵leetcode54open in new window

给你一个 mn 列的矩阵matrix ,请按照顺时针螺旋顺序 ,返回矩阵中的所有元素。

var spiralOrder = function(matrix) {

  if (matrix.length < 1) return matrix;
  let left = 0,
      right = matrix[0].length - 1,
      top = 0,
      bottom = matrix.length - 1,
      direction = "right", // 当前要遍历的方向
      result = [];
  while(left <= right && top <= bottom) {
    // 向左判断
    if (direction === 'right') {
      for (let i = left; i <= right; i++) {
        result.push(matrix[top][i])
      }
      top++
      direction = 'down'
    // 向下判断
    } else if (direction === 'down') {
      for (let i = top; i <= bottom; i++) {
        result.push(matrix[i][right])
      }
      right--
      direction = 'left'
    // 向左判断
    } else if (direction === 'left') {
      for (let i = right; i >= left; i--){
        result.push(matrix[bottom][i])
      }
      bottom--
      direction = 'up'
    // 向上
    } else {
      for (let i = bottom; i >= top; i--){
        result.push(matrix[i][left])
      }
      left++
      direction = 'right'
    }
  }
  return result
};

LRU算法leetcode146open in new window

var LRUCache = function (capacity) {
  this.cache = new Map();
  this.capacity = capacity;
};

LRUCache.prototype.get = function (key) {
  if (this.cache.has(key)) {
    // 存在即更新
    let temp = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key, temp);
    return temp;
  }
  return -1;
};

LRUCache.prototype.put = function (key, value) {
  if (this.cache.has(key)) {
    // 存在即更新(删除后加入)
    this.cache.delete(key);
  } else if (this.cache.size >= this.capacity) {
    // 不存在即加入
    // 缓存超过最大值,则移除最近没有使用的
    this.cache.delete(this.cache.keys().next().value);
  }
  this.cache.set(key, value);
};
小红包免费领
小礼物走一走
Last Updated:
Contributors: slbyml
部分内容来源于网络,如有侵权,请留言或联系994917123@qq.com;访问量:waiting;访客数:waiting