[LeetCode] Array With Elements Not Equal to Average of Neighbors

1968. Array With Elements Not Equal to Average of Neighbors

You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.

More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i].

Return any rearrangement of nums that meets the requirements.

  • greedy solution
  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> rearrangeArray(vector<int>& A) {
int n = A.size();
for(int i = 1; i < n - 1; i++) {
if(A[i - 1] + A[i + 1] == 2 * A[i])
swap(A[i], A[i + 1]);
}
for(int i = n - 2; i >= 1; i--) {
if(A[i - 1] + A[i + 1] == 2 * A[i])
swap(A[i], A[i - 1]);
}
return A;
}
};
  • wiggle sort solution (based on two pointer)
  • Time : O(nlogn)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
vector<int> rearrangeArray(vector<int>& A) {
auto B = A;
sort(begin(B), end(B));
int l = 0, r = A.size() - 1;
for(int i = 0; i < A.size(); i++) {
if(i & 1) A[i] = B[r--];
else A[i] = B[l++];
}
return A;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/09/PS/LeetCode/array-with-elements-not-equal-to-average-of-neighbors/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.