forked from black-shadows/LeetCode-Topicwise-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray-with-elements-not-equal-to-average-of-neighbors.cpp
47 lines (44 loc) · 1.47 KB
/
array-with-elements-not-equal-to-average-of-neighbors.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Time: O(n) ~ O(n^2), O(n) on average
// Space: O(1)
// Tri Partition (aka Dutch National Flag Problem) with virtual index solution
class Solution {
public:
vector<int> rearrangeArray(vector<int>& nums) {
int mid = (size(nums) - 1) / 2;
nth_element(begin(nums), begin(nums) + mid, end(nums)); // O(n) ~ O(n^2) time
reversedTriPartitionWithVI(nums, nums[mid]); // O(n) time, O(1) space
return nums;
}
private:
void reversedTriPartitionWithVI(vector<int>& nums, int val) {
const int N = size(nums) / 2 * 2 + 1;
#define Nums(i) nums[(1 + 2 * (i)) % N]
for (int i = 0, j = 0, n = size(nums) - 1; j <= n;) {
if (Nums(j) > val) {
swap(Nums(i++), Nums(j++));
} else if (Nums(j) < val) {
swap(Nums(j), Nums(n--));
} else {
++j;
}
}
}
};
// Time: O(nlogn)
// Space: O(n)
// Sorting and reorder solution
class Solution2 {
public:
vector<int> rearrangeArray(vector<int>& nums) {
int mid = (size(nums) - 1) / 2;
sort(begin(nums), end(nums)); // O(nlogn) time
vector<int> result(size(nums)); // O(n) space
for (int i = 0, smallEnd = mid; i < size(nums); i += 2, --smallEnd) {
result[i] = nums[smallEnd];
}
for (int i = 1, largeEnd = size(nums) - 1; i < size(nums); i += 2, --largeEnd) {
result[i] = nums[largeEnd];
}
return result;
}
};