程序员面试金典---5

零矩阵

思路:

设置两个列表记录哪里需要置零,然后对其改变即可

class Solution:
 def setZeroes(self, matrix: List[List[int]]) -> None:
     """
     Do not return anything, modify matrix in-place instead.
     """
     n, m = len(matrix), len(matrix[0])
     # 判断列表
     rows, cols = [False] * n, [False] * m

     for i in range(n):
         for j in range(m):
             if matrix[i][j] == 0:
                 # 某一个为0,将其行列记下
                 rows[i] = cols[j] = True

     for i in range(n):
         for j in range(m):
             # 如果某一个的行列别记下了为0,则直接置为0
             matrix[i][j] =  0 if rows[i] or cols[j] else matrix[i][j]

动物收容所

思路:拿个数组装着动物, 拿Any的就直接从头部拿, 拿猫狗就要循环拿到该种类的动物 没有就返回[-1, -1]

var AnimalShelf = function() {
  this.animals = []
};

/** 
 * @param {number[]} animal
 * @return {void}
 */
AnimalShelf.prototype.enqueue = function(animal) {
   this.animals.push(animal)
};

/**
 * @return {number[]}
 */
AnimalShelf.prototype.dequeueAny = function() {
  if(this.animals.length === 0) return [-1, -1]
  return this.animals.shift()
};

/**
 * @return {number[]}
 */
AnimalShelf.prototype.dequeueDog = function() {
  let i = 0
  let len = this.animals.length
  while(i < len && this.animals[i][1] !== 1){
    i++
  }
  if(i >= len){
    return [-1, -1]
  }
  return this.animals.splice(i, 1)[0]
};

/**
 * @return {number[]}
 */
AnimalShelf.prototype.dequeueCat = function() {
  let i = 0
  let len = this.animals.length
  while(i < len && this.animals[i][1] !== 0){
    i++
  }
  if(i >= len){
    return [-1, -1]
  }
  return this.animals.splice(i, 1)[0]
};

/**
 * Your AnimalShelf object will be instantiated and called as such:
 * var obj = new AnimalShelf()
 * obj.enqueue(animal)
 * var param_2 = obj.dequeueAny()
 * var param_3 = obj.dequeueDog()
 * var param_4 = obj.dequeueCat()
 */
posted @   楸枰~  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示