给出一个整数数组,对数组进行排序,使arr1 >= arr2 <= arr3 >= arr4 <= arr5 ...
然后返回数组
示例:
给出[1,2,3,4]
可能的结果:
1:[2,1,4,3]
2:[4,1,3,2]
答案 0 :(得分:1)
这就是我最天真的实现方式:
const arr = [4, 2, 1, 3, 5];
const sorted = arr.sort((a, b) => a - b);
const left = sorted.slice(0, sorted.length / 2);
const right = sorted.slice(sorted.length / 2);
const merged = [];
for (let i = 0; i < right.length; ++i) {
merged.push(right[i]);
if (i < left.length) {
merged.push(left[i]);
}
}
console.log(merged);
它的作用:
视觉解释:
初始状态:
left right
[1, 2] [3, 4, 5]
合并:
步骤1:
left right
[1, 2] [4, 5]
merged
[3]
第2步:
left right
[2] [4, 5]
merged
[3, 1]
第3步:
left right
[2] [5]
merged
[3, 1, 4]
第4步:
left right
[] [5]
merged
[3, 1, 4, 2]
第5步:
left right
[] []
merged
[3, 1, 4, 2, 5]
答案 1 :(得分:1)
从排序数组开始:
sort($numbers);
通过从输入数组的开头和结尾取数字之间交替,将数字附加到结果数组中。
$i = 1;
// remove elements from $numbers array until it is empty
while ($numbers) {
if ($i++ % 2) {
// on odd iterations, pull an item from the end of $numbers (highest numbers)
$result[] = array_pop($numbers);
} else {
// on even iterations, pull an item from the beginning of $numbers (lowest numbers)
$result[] = array_shift($numbers);
}
}