原题链接在这里:https://leetcode.com/problems/wiggle-sort/
题目:
Given an unsorted array nums
, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]...
.
Example:
Input: nums = [3,5,2,1,6,4]
Output: One possible answer is [3,5,1,6,2,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; i<nums.length; i++){ 7 if(i%2 == 1){ 8 if(nums[i] < nums[i-1]){ 9 swap(nums, i-1, i); 10 } 11 }else{ 12 if(nums[i] > nums[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 }