Question
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]
.
Solution 1
仔细观察题目,有个条件很重要就是nums[0] <= nums[1] >= nums[2] <= nums[3]...
.也就是说对于奇书的 i 我们要保证 nums[i - 1] <= nums[i] <= nums[i + 1] 所以第一个想法是1. 先排序 2. 交换每个nums[i] 和 nums[i + 1]
Time complexity O(n log n).
1 public class Solution { 2 public void wiggleSort(int[] nums) { 3 if (nums == null || nums.length < 2) 4 return; 5 Arrays.sort(nums); 6 for (int i = 1; i < nums.length - 1; i = i + 2) { 7 int tmp = nums[i]; 8 nums[i] = nums[i + 1]; 9 nums[i + 1] = tmp; 10 } 11 } 12 }
Solution 2
分奇偶来思考。
如果i是奇数,那么nums[i]应该大于nums[i - 1],否则交换
如果i是偶数,那么nums[i]应该小于nums[i - 1],否则交换
1 public class Solution { 2 public void wiggleSort(int[] nums) { 3 if (nums == null) 4 return; 5 for (int i = 1; i < nums.length; i++) { 6 if (i % 2 == 1) { 7 if (nums[i] < nums[i - 1]) 8 swap(nums, i, i - 1); 9 } else { 10 if (nums[i] > nums[i - 1]) 11 swap(nums, i, i - 1); 12 } 13 } 14 } 15 private void swap(int[] nums, int x, int y) { 16 int tmp = nums[x]; 17 nums[x] = nums[y]; 18 nums[y] = tmp; 19 } 20 }