#1968
Array With Elements Not Equal to Average of Neighbors
specialist · 865 · lc medium +31 · verified · 50.6% accepted · 660 likes · top 39%
Description
Given a 0-indexed array nums of distinct integers, rearrange the elements so that no interior element equals the mean of its two neighbors. Concretely, for every index i with 1 <= i < nums.length - 1, the value (nums[i-1] + nums[i+1]) / 2 must differ from nums[i].
Return any valid arrangement of nums.
Example 1:
Input: nums = [1,2,3,4,5]
Output: [1,2,4,5,3]
Explanation:
When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
Example 2:
Input: nums = [6,2,0,9,7]
Output: [9,7,6,2,0]
Explanation:
When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.
Note that the original array [6,2,0,9,7] also satisfies the conditions.
Code
1
2
3