不必了

文章 评论 浏览 29

◇不必了。 2022-05-04 13:56:41

订阅发布、任务机制(异步串行)

const _sayHi = Symbol('_sayHi') // 私有
class LazyManClass {
  constructor(name) {
    this.name = name
    this[_sayHi](name)

    this.handlerQueue = []
    this.tasks = []
    setTimeout(() => this.runTasks())
  }

  [_sayHi](name) {
    console.log('Hi I am ' + name)
  }

  // 异步串行
  runTasks() {
    const len = this.tasks.length
    const next = (i) => {
      if(i==len) return
      this.tasks[i](() => next(i+1))
    }
    next(0)
  }

  clear() {
    this.handlerQueue = []
  }

  run() {
    this.handlerQueue.forEach((fn) => fn())
    this.clear()
  }

  sleep(time) {
    this.run()

    const task = (cb) => {
      console.log('等待了' +  time + '秒')
      setTimeout(() =>{
        this.run()
        cb()
      }, time*1000)
    }
    this.tasks.push(task)
    return this
  }

  eat(food) {
    this.handlerQueue.push(() => console.log('I am eating' + food))
    return this
  }

  sleepFirst(time) {
    const queue = [...this.handlerQueue]
    const task = (cb) => {
      console.log('等待了' +  time + '秒')
      setTimeout(() =>{
        queue.forEach((fn) => fn())
        cb()
      }, time*1000)
    }
    this.tasks.push(task)
    this.handlerQueue = []
    return this
  }
}
function LazyMan(name) {
  return new LazyManClass(name);
}
// LazyMan('Tony');
// LazyMan('Tony').sleep(3).eat('lunch');
// LazyMan('Tony').eat('lunch').sleep(3).eat('dinner')
LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(2).sleep(3).eat('junk food');

第 56 题:要求设计 LazyMan 类,实现以下功能

◇不必了。 2022-05-04 13:00:12

@xiongchenf 兄弟,你用了sort之后时间复杂度已经是O(nlog(n))了,不符合题目O(log(m+n))

第 93 题:给定两个大小为 m 和 n 的有序数组 nums1 和 nums2,请找出这两个有序数组的中位数。要求算法的时间复杂度为 O(log(m+n))。

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文