Skip to content

Commit 88f3aef

Browse files
authored
Create array-with-elements-not-equal-to-average-of-neighbors.cpp
1 parent 17b7bcc commit 88f3aef

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Time: O(n) ~ O(n^2), O(n) on average
2+
// Space: O(1)
3+
4+
// Tri Partition (aka Dutch National Flag Problem) with virtual index solution
5+
class Solution {
6+
public:
7+
vector<int> rearrangeArray(vector<int>& nums) {
8+
int mid = (size(nums) - 1) / 2;
9+
nth_element(begin(nums), begin(nums) + mid, end(nums)); // O(n) ~ O(n^2) time
10+
reversedTriPartitionWithVI(nums, nums[mid]); // O(n) time, O(1) space
11+
return nums;
12+
}
13+
14+
private:
15+
void reversedTriPartitionWithVI(vector<int>& nums, int val) {
16+
const int N = size(nums) / 2 * 2 + 1;
17+
#define Nums(i) nums[(1 + 2 * (i)) % N]
18+
for (int i = 0, j = 0, n = size(nums) - 1; j <= n;) {
19+
if (Nums(j) > val) {
20+
swap(Nums(i++), Nums(j++));
21+
} else if (Nums(j) < val) {
22+
swap(Nums(j), Nums(n--));
23+
} else {
24+
++j;
25+
}
26+
}
27+
}
28+
};
29+
30+
// Time: O(nlogn)
31+
// Space: O(n)
32+
// Sorting and reorder solution
33+
class Solution2 {
34+
public:
35+
vector<int> rearrangeArray(vector<int>& nums) {
36+
int mid = (size(nums) - 1) / 2;
37+
sort(begin(nums), end(nums)); // O(nlogn) time
38+
vector<int> result(size(nums)); // O(n) space
39+
for (int i = 0, smallEnd = mid; i < size(nums); i += 2, --smallEnd) {
40+
result[i] = nums[smallEnd];
41+
}
42+
for (int i = 1, largeEnd = size(nums) - 1; i < size(nums); i += 2, --largeEnd) {
43+
result[i] = nums[largeEnd];
44+
}
45+
return result;
46+
}
47+
};

0 commit comments

Comments
 (0)