在 JavaScript 中重新排列陣列元素
問題
JavaScript 函式使用陣列的第一項和唯一一個引數作為陣列文字 arr,其中包含一些相鄰的重複項。
我們的函式應該重新排列陣列元素,以確保陣列中沒有兩個元素相等。我們的函式應該返回重新排列後的陣列,假設存在至少一種可能的排列方式。
例如,如果輸入函式為 -
const arr = [7, 7, 7, 8, 8, 8];
那麼輸出應該是 -
const output = [7, 8, 7, 8, 7, 8];
輸出解釋
還可能存在其他可能的排列。
示例
程式碼如下 -
const arr = [7, 7, 7, 8, 8, 8];
const rearrangeArray = (arr = []) => {
const map = arr.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1 return acc;
}, {});
const keys = Object.keys(map).sort((a, b) => map[a] - map[b]);
const res = [];
let key = keys.pop();
for(let i = 0; i < arr.length; i += 2){
if(map[key] <= 0){
key = keys.pop();
};
map[key] -= 1;
res[i] = Number(key);
};
for(let i = 1; i < arr.length; i += 2){
if(map[key] <= 0){
key = keys.pop();
};
map[key] -= 1;
res[i] = Number(key);
};
return res;
};
console.log(rearrangeArray(arr));輸出
控制檯中的輸出為 -
[ 8, 7, 8, 7, 8, 7 ]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP