Skip to content

Instantly share code, notes, and snippets.

@karlding
Created January 22, 2016 22:39
Show Gist options
  • Save karlding/74cb6b22321ed5f3e156 to your computer and use it in GitHub Desktop.
Save karlding/74cb6b22321ed5f3e156 to your computer and use it in GitHub Desktop.
Because I'm silly and tried to use std::swap and make some "smart" optimizations without thinking on a HackerRank problem :(
// print out array in zigzag format
// time: O(n log n) = O(n log n) + O(n log n) + O(n)
// space: O(3n)
std::vector<int> zigZagArray(std::vector<int> intArray) {
std::vector<int> v(intArray);
// sort descending order
std::sort(intArray.rbegin(), intArray.rend());
// sort asc
std::sort(v.begin(), v.end());
std::vector<int> tmp;
int a = 0, b = 0;
for (int i = 0; i < v.size(); ++i) {
if (i % 2 == 0) {
tmp.push_back(intArray[a++]);
} else {
tmp.push_back(v[b++]);
}
}
return tmp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment