Skip to content

Commit

Permalink
Update wiggle-sort-ii.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 committed Jan 1, 2016
1 parent b664834 commit 7546b9e
Showing 1 changed file with 27 additions and 9 deletions.
36 changes: 27 additions & 9 deletions C++/wiggle-sort-ii.cpp
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// Time: O(n) ~ O(n^2)
// Space: O(1)

// Dutch flag sorting with virtual index solution.
// Dutch flag sorting with virtual index solution. (44ms)
class Solution {
public:
void wiggleSort(vector<int>& nums) {
int mid = (nums.size() - 1) / 2;
nth_element(nums.begin(), nums.begin() + mid, nums.end());
nth_element(nums.begin(), nums.begin() + mid, nums.end()); // O(n) ~ O(n^2)
reversedDutchFlagSortWithVI(nums, nums[mid]);
}

Expand All @@ -27,20 +27,19 @@ class Solution {

// Time: O(n) ~ O(n^2)
// Space: O(n)
// Dutch flag sorting solution.
// Dutch flag sorting solution. (64ms)
class Solution2 {
public:
void wiggleSort(vector<int>& nums) {
const int n = nums.size();
int mid = (n - 1) / 2;
nth_element(nums.begin(), nums.begin() + mid, nums.end());
int mid = (nums.size() - 1) / 2;
nth_element(nums.begin(), nums.begin() + mid, nums.end()); // O(n) ~ O(n^2)
dutchFlagSort(nums, nums[mid]);

vector<int> res(n);
for (int i = 0, smallEnd = mid; i < n; i += 2, --smallEnd) {
vector<int> res(nums.size());
for (int i = 0, smallEnd = mid; i < nums.size(); i += 2, --smallEnd) {
res[i] = nums[smallEnd];
}
for (int i = 1, largeEnd = n - 1; i < n; i += 2, --largeEnd) {
for (int i = 1, largeEnd = nums.size() - 1; i < nums.size(); i += 2, --largeEnd) {
res[i] = nums[largeEnd];
}
nums = res;
Expand All @@ -58,3 +57,22 @@ class Solution2 {
}
}
};

// Time: O(nlogn)
// Space: O(n)
// Sorting and reorder solution. (64ms)
class Solution3 {
public:
void wiggleSort(vector<int>& nums) {
int mid = (nums.size() - 1) / 2;
sort(nums.begin(), nums.end());
vector<int> res(nums.size());
for (int i = 0, smallEnd = mid; i < nums.size(); i += 2, --smallEnd) {
res[i] = nums[smallEnd];
}
for (int i = 1, largeEnd = nums.size() - 1; i < nums.size(); i += 2, --largeEnd) {
res[i] = nums[largeEnd];
}
nums = res;
}
};

0 comments on commit 7546b9e

Please sign in to comment.