Mô tả vấn đề
Hàm JavaScript nhận vào mảng số arr (độ dài chẵn). Trả về true nếu có thể sắp xếp lại sao cho arr[2*i+1] = 2*arr[2*i] với mọi 0 ≤ i < length/2.
Ví dụ, nếu đầu vào là:
const arr = [4, -2, 2, -4];
Thì đầu ra nên là:
const output = true;
Giải thích đầu ra
Có thể nhóm [-2,-4] và [2,4] thành [-2,-4,2,4] hoặc [2,4,-2,-4].
Ví dụ minh họa
Mã thực hiện (bản đồ tần suất + sắp xếp):
const arr = [4, -2, 2, -4];
const canRearrange = (arr = []) => {
const map = arr.reduce((acc, num) => {
acc[num] = (acc[num] || 0) + 1;
return acc;
}, {});
const keys = Object.keys(map)
.map(key => Number(key))
.sort((a, b) => a - b);
for (const key of keys) {
if (key < 0) {
while (map[key] > 0) {
if (map[key / 2] > 0) {
map[key] -= 1;
map[key / 2] -= 1;
} else {
return false;
}
}
} else {
while (map[key] > 0) {
if (map[key * 2] > 0) {
map[key] -= 1;
map[key * 2] -= 1;
} else {
return false;
}
}
}
}
return true;
};
console.log(canRearrange(arr));Đầu ra
Kết quả trong console:
true