感觉这样也可以的,效率怎么样?

来源:3-4 卡牌分组-原理讲解

木南1988

2019-02-14

export default (arr) => {
arr.sort((a, b) => a - b)
let min = Number.MAX_SAFE_INTEGER
const distLen = []
for (let i = 0, tmpLen = 1; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] === arr[i]) {
tmpLen++
} else {
if (tmpLen < min) {
min = tmpLen
}
distLen.push(tmpLen)
i = j
break
}
}
}
return distLen.every(num => (num % min === 0))
}

感觉这样也是可以的,效率怎么样呢?

写回答

2回答

木南1988

提问者

2019-02-19

var hasGroupsSizeX = function(deck) {

  const countMap = {};

  deck.forEach((num) => {

    if (countMap[num] === undefined) countMap[num] = 0

    countMap[num] = countMap[num] + 1

  })

  const distLen = Object.values(countMap)

  const isSingle = !!~distLen.indexOf(1)

  

  const hasSame = (nums = []) => {

    const min = Math.min.apply(null, nums)

    if (nums.every((num) => (num % min === 0))) return true

    for (let i = 2; i <= Math.floor(min / 2); i++) {

      if (nums.every(numItem => (numItem % i === 0))) {

        return true

      }

    }

    return false

  }

  if (isSingle) return false

  return hasSame(distLen)

};

我把漏洞修复了下

0
0

快乐动起来呀

2019-02-15

这个和源代码原理是一样的,只是写法不同,这个写法很赞

0
1
木南1988
var hasGroupsSizeX = function(deck) { const countMap = {}; deck.forEach((num) => { if (countMap[num] === undefined) countMap[num] = 0 countMap[num] = countMap[num] + 1 }) const distLen = Object.values(countMap) const isSingle = !!~distLen.indexOf(1) const hasSame = (nums = []) => { const min = Math.min.apply(null, nums) if (nums.every((num) => (num % min === 0))) return true for (let i = 2; i <= Math.floor(min / 2); i++) { if (nums.every(numItem => (numItem % i === 0))) { return true } } return false } if (isSingle) return false return hasSame(distLen) }; 之前的还是有漏洞 我又重新优化了一下
2019-02-19
共1条回复

JavaScript版 数据结构与算法

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

2467 学习 · 395 问题

查看课程