1: class Solution {
2: public:
3: void wiggleSort(vector<int>& nums) {
4: vector<int> tmp(nums);
5: sort(tmp.begin(), tmp.end());
6: for (int i = nums.size()-1, j = 0, k = (nums.size()+1)/2; i >= 0; i--) {
7: nums[i] = tmp[i & 1 ? k++ : j++];
8: }
9: }
10: };
I've tried to sort it in place by swapping but realized that there is problem. The merge algorithm above shifts the small number to right however, the swapping will swap the small numbers to end which causes difficulty to find the termination of swapping.
For the follow up question, I have no clue about the virtual indexing algorithm that top rated solution mentions.
No comments:
Post a Comment