原题链接在这里:
题目:
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]
.
题解:
当 i 是奇数时,若nums[i] < nums[i-1], 互换。
当 i 是偶数时,若nums[i] > nums[i-1], 互换。
Time Complexity: O(n). Space: O(1).
AC Java:
1 public class Solution { 2 public void wiggleSort(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return; 5 } 6 for(int i = 1; inums[i-1]){13 swap(nums, i-1, i);14 }15 }16 }17 }18 private void swap(int [] nums, int i, int j){19 int temp = nums[i];20 nums[i] = nums[j];21 nums[j] = temp;22 }23 }
跟上