给你一个 下标从 0 开始 的数组 nums ,数组由若干 互不相同的 整数组成。你打算重新排列数组中的元素以满足:重排后,数组中的每个元素都 不等于 其两侧相邻元素的 平均值 。
更公式化的说法是,重新排列的数组应当满足这一属性:对于范围 1 <= i < nums.length - 1 中的每个 i ,(nums[i-1] + nums[i+1]) / 2 不等于 nums[i] 均成立 。
返回满足题意的任一重排结果。
示例 1:
输入:nums = [1,2,3,4,5]
输出:[1,2,4,5,3]
解释:
i=1, nums[i] = 2, 两相邻元素平均值为 (1+4) / 2 = 2.5
i=2, nums[i] = 4, 两相邻元素平均值为 (2+5) / 2 = 3.5
i=3, nums[i] = 5, 两相邻元素平均值为 (4+3) / 2 = 3.5
示例 2:
输入:nums = [6,2,0,9,7]
输出:[9,7,6,2,0]
解释:
i=1, nums[i] = 7, 两相邻元素平均值为 (9+6) / 2 = 7.5
i=2, nums[i] = 6, 两相邻元素平均值为 (7+2) / 2 = 4.5
i=3, nums[i] = 2, 两相邻元素平均值为 (6+0) / 2 = 3
java代码:
class Solution {
public int[] rearrangeArray(int[] nums) {
int length = nums.length;
if (length <= 2) {
return nums;
}
int[] res = new int[nums.length];
if (length % 2 == 0) {
toMaxHeap(nums, length - 1);
res = midTravel(nums, length - 1);
if (nums[length-1] > res[length-2]) {
res[length-1] = nums[length-1];
} else {
res[length-1] = res[length-2];
res[length-2] = nums[length-1];
}
} else {
toMaxHeap(nums, length);
res = midTravel(nums, length);
}
return res;
}
public int[] midTravel(int[] nums, int length) {
List temp = new ArrayList<>();
midTravel(nums, length, temp, 0);
int[] res = new int[nums.length];
for (int i = 0; i < length; i++) {
res[i] = temp.get(i);
}
return res;
}
// 中序遍历大顶堆
public void midTravel(int[] nums, int length, List res, int i) {
int left = 2*i+1;
int right = left + 1;
if (left < length) {
midTravel(nums, length, res, left);
}
res.add(nums[i]);
if (right < length) {
midTravel(nums, length, res, right);
}
}
// 构建一个大顶堆
private void toMaxHeap(int[] nums, int length) {
for (int i = length / 2 - 1; i >= 0; i--) {
swapMaxHeap(nums, i, length);
}
}
private void swapMaxHeap(int[] nums, int i, int length) {
int temp = nums[i];
for (int k = 2*i+1; k < length; k = 2*k+1) {
if (k+1 < length && nums[k] < nums[k+1]) {
k++;
}
if (nums[k] < temp) {
break;
} else {
nums[i] = nums[k];
i = k;
}
}
nums[i] = temp;
}
}