题目
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
答案
class Solution {
// key: odd element needs to be greater than both sides while even elements need to be smaller than both sides
// odd1 even1 odd2 even2 odd3 even3
public void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public void wiggleSort(int[] nums) {
for(int i = 0; i < nums.length; i+=2) {
if(i > 0 && nums[i] > nums[i - 1]) swap(nums, i, i - 1);
if(i < nums.length-1 && nums[i] > nums[i + 1]) swap(nums, i, i + 1);
}
}
}
网友评论