[LeetCode] Wiggle Sort

Wiggle Sort

Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....

For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].

贪心,数学归纳法很容易证明出来。

 1 class Solution {
 2 public:
 3     void wiggleSort(vector<int>& nums) {
 4         int flag = 1;
 5         for (int i = 1; i < nums.size(); ++i) {
 6             if (nums[i] * flag < nums[i-1] * flag) 
 7                 swap(nums[i], nums[i-1]);
 8             flag = -flag;
 9         }
10     }
11 };

 

posted @ 2015-09-10 18:37  Eason Liu  阅读(1367)  评论(0编辑  收藏  举报