[LeetCode] 280. 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].
给一个没有排序的数组,将其重新排序成nums[0] <= nums[1] >= nums[2] <= nums[3]....的样子,要求in-place。
解法:遍历一遍数组, 如果是奇数位置并且其值比下一个大,则交换其值, 如果是偶数位置并且其值比下一个小, 则交换其值. 时间复杂度是O(N)。注意index和实际的位置差1,所以奇偶相反。
Java:
public class Solution { public void wiggleSort(int[] nums) { if (nums == null || nums.length < 2) return; for (int i = 1; i < nums.length; i++) { if ((i % 2 == 0 && nums[i] > nums[i - 1]) || (i % 2 == 1 && nums[i] < nums[i - 1])) { int tmp = nums[i]; nums[i] = nums[i - 1]; nums[i - 1] = tmp; } } } }
Java:
public class Solution { public void wiggleSort(int[] nums) { if (nums == null || nums.length == 0) { return; } for (int i = 1; i < nums.length; i++) { if (i % 2 == 1) { if (nums[i] < nums[i - 1]) { swap(nums, i); } } else { if (nums[i] > nums[i - 1]) { swap(nums, i); } } } } private void swap(int[] nums, int i) { int tmp = nums[i - 1]; nums[i - 1] = nums[i]; nums[i] = tmp; } }
Python:
# Time: O(n) # Space: O(1) class Solution(object): def wiggleSort(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ for i in xrange(1, len(nums)): if ((i % 2) and nums[i - 1] > nums[i]) or \ (not (i % 2) and nums[i - 1] < nums[i]): # Swap unordered elements. nums[i - 1], nums[i] = nums[i], nums[i - 1]
C++:
// Time: O(n) // Space: O(1) class Solution { public: void wiggleSort(vector<int>& nums) { for (int i = 1; i < nums.size(); ++i) { if (((i % 2) && nums[i] < nums[i - 1]) || (!(i % 2) && nums[i] > nums[i - 1])) { // Swap unordered elements. swap(nums[i], nums[i - 1]); } } } };
C++:
// Time Complexity O(nlgn) class Solution { public: void wiggleSort(vector<int> &nums) { sort(nums.begin(), nums.end()); if (nums.size() <= 2) return; for (int i = 2; i < nums.size(); i += 2) { swap(nums[i], nums[i - 1]); } } };
C++:
// Time Complexity O(n) class Solution { public: void wiggleSort(vector<int> &nums) { if (nums.size() <= 1) return; for (int i = 1; i < nums.size(); ++i) { if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) { swap(nums[i], nums[i - 1]); } } } };
类似题目:
[LeetCode] Wiggle Sort II 摆动排序 II
All LeetCode Questions List 题目汇总