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]
.
链接: http://leetcode.com/problems/wiggle-sort/
题解:
Wiggle排序数组。按照题意写就可以了。 还可以简化,要多学习Stefan的代码。
Time Complexity - O(n), Space Complexity - O(1)
public class Solution { public void wiggleSort(int[] nums) { for(int i = 1; i < nums.length; i++) { if(i % 2 == 1) { if(nums[i] < nums[i - 1]) { swap(nums, i); } } else { if(i != 0 && 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; } }
二刷:
方法和一刷一样。在i % 2 == 1或者 == 0的时候作交换的判断,交换完毕以后仍然保持这是一个本地化操作就可以了。交换的时候是用 i和 i - 1来交换
Java:
Time Complexity - O(n), Space Complexity - O(1)
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; } }
三刷:
跟前面一样,也是直接编写。
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; } } } }
Reference:
https://leetcode.com/discuss/57113/java-o-n-solution
https://leetcode.com/discuss/57206/java-o-n-10-lines-consice-solution
https://leetcode.com/discuss/60824/java-python-o-n-time-o-1-space-solution-3-lines
https://leetcode.com/discuss/57118/easy-code-of-python