程序员面试金典---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 @ 2023-04-14 22:56  楸枰~  阅读(19)  评论(0)    收藏  举报