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].
一刷
題解:一個特別簡單的思路侍筛,如果index為奇數(shù)萤皂,且小于左邊,交換匣椰;
如果如果index為偶數(shù)裆熙,且大于左邊,交換窝爪。
public class Solution {
public void wiggleSort(int[] nums) {
if(nums.length<=1) return;
for(int i=1; i<nums.length; i++){
if(i%2 == 1 && nums[i] < nums[i-1]) swap(nums, i, i-1);
else if(i%2 == 0 && nums[i]>nums[i-1]) swap(nums, i, i-1);
}
}
private void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
二刷
用bit operation來提速
public class Solution {
public void wiggleSort(int[] nums) {
for (int i = 1; i < nums.length; i++)
if (((i & 1) == 0) == (nums[i - 1] < nums[i])) xwap(nums, i);
}
private void xwap(int[] a, int i) {
int t = a[i]; a[i] = a[i - 1]; a[i - 1] = t;
}
}
三刷
同上