改了个LeetCode通过的,但效率好低

来源:7-5 最大矩阵-代码实操(2)

诺巴蒂

2019-11-20

var maximalRectangle = function (arr) {
  if (arr.length === 0) {
    return 0
  }

  let result = []
  let reg = /1{1,}/g
  arr = arr.map(item => {
    let str = item.join('')
    let r = reg.exec(str)
    let rs = []
    while (r) {
      rs.push([r.index, r.index + r[0].length - 1])
      r = reg.exec(str)
    }
    return rs
  })

  let getRect = (arr, n = 1) => {
    let top = arr.pop()
    if (n === 1 || arr.length === 1) {
      top.forEach(item => {
        result.push(1 * (item[1] - item[0] + 1))
      })
    }
    if (arr.length > 0) {
      let next = arr.pop()
      let tt
      let nn
      let start
      let end
      let currentLine = []
      for (let i = 0, il = top.length; i < il; i++) {
        tt = top[i]
        for (let j = 0, jl = next.length; j < jl; j++) {
          nn = next[j]
          start = Math.max(tt[0], nn[0])
          end = Math.min(tt[1], nn[1])
          width = end - start
          if (width >= 0) {
            currentLine.push([start, end])
          }
        }
      }
      if (currentLine.length === 0) {
        top.forEach(item => {
          result.push(n * (item[1] - item[0] + 1))
        })
      } else {
        arr.push(currentLine)
        currentLine.forEach(item => {
          result.push((n + 1) * (item[1] - item[0] + 1))
        })
        if (arr.length > 1) {
          getRect(arr, n + 1)
        }
      }
    }
  }


  while (arr.length >= 1) {
    if (arr.length === 1) {
      arr[0].forEach(item => {
        result.push(1 * (item[1] - item[0] + 1))
      })
    } else {
      getRect([].concat(arr))
    }
    arr.pop()
  }

  let max = 0
  let item = result.pop()
  while (item) {
    if (item > max) {
      max = item
    }
    item = result.pop()
  }
  return max > 0 ? max : 0
};

执行用时 :
152 ms
, 在所有 javascript 提交中击败了
19.03%
的用户

内存消耗 :
49.2 MB
, 在所有 javascript 提交中击败了
5.00%
的用户

要考虑一行的情况和单个的情况,我把所有矩阵都找出来了,应该还能优化。。。有点花时间,下回不这么较真了!这要面试写完这个估计已经挂了

写回答

1回答

快乐动起来呀

2019-11-24

同学面试这么写为什么要挂呢?毕竟很多人写不出来呀,哈哈,再者面试不是只看结果,更看重的是思考的方向(思维),写码的能力等等,如果只看结果那刷题的人都是有能力的?

0
3
诺巴蒂
回复
快乐动起来呀
弱弱的问一句,这个课的难度离字节跳动的前端算法难度相比有多大差距
2019-11-28
共3条回复

JavaScript版 数据结构与算法

填补前端同学的算法短板,掌握面试中最常见的算法与数据结构

2467 学习 · 395 问题

查看课程