1968. Array With Elements Not Equal to Average of Neighbors - Medium
前往題目
想法
- 把數字小於等於中位數的都放到奇數位,其餘放到偶數位
思路
- 排序
- 小和大的數字交錯,這樣每個數字就會被比他自己大的兩個數字包圍或是兩個比他自己小的數字包圍,所以可以保證絕對不會等於兩數相加除二
Code
class Solution {
public int[] rearrangeArray(int[] nums) {
Arrays.sort(nums);
int l = 0, r = nums.length - 1;
int[] res = new int[nums.length];
// Go through the array
// By the sequence of small, big, small, big etc
for (int i = 0; i < nums.length; ++i) {
// Add a small number
res[i] = nums[l];
++l;
// Prevent cross the bound
if (l <= r) {
++i;
res[i] = nums[r];
--r;
}
}
return res;
}
}
1968. Array With Elements Not Equal to Average of Neighbors - Medium
https://f88083.github.io/2024/06/02/1968-Array-With-Elements-Not-Equal-to-Average-of-Neighbors-Medium/