按组重新排列卡牌
问题
你需要编写一个 JavaScript 函数,该函数的第一个参数是数字数组 arr,第二个参数是数字 num。
数组中的数字范围为 [1, 13],边界值包含在内,表示纸牌的从 1 开始的索引。
你的函数应该确定是否有一种方法可以将纸牌重新排列成组,使得每组大小为 num,且由 num 张连续的纸牌组成。
例如,如果函数的输入如下
输入
const arr = [1, 4, 3, 2]; const num = 2;
输出
const output = 2;
输出说明
因为纸牌可以重新排列为 [1, 2], [3, 4]
示例
以下是代码 −
const arr = [1, 4, 3, 2];
const num = 2;
const canRearrange = (arr = [], num = 1) => {
const find = (map, n, num) => {
let j = 0
while(j < num) {
if(!map[n + j]) return false
else map[n + j] -= 1
j++
}
return true
}
let map = {}
arr.sort(function(a, b) {return a - b})
for(let n of arr) {
map[n] = map[n] ? map[n] + 1 : 1
}
for(let n of arr) {
if(map[n] === 0 || find(map, n, num)) continue
else return false
}
return true
};
console.log(canRearrange(arr, num));输出
true
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP