- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 46 lines of Java from the credited upstream file 324.java.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public void wiggleSort(int[] nums) {3 final int n = nums.length;4 final int median = findKthLargest(nums, (n + 1) / 2);5 for (int i = 0, j = 0, k = n - 1; i <= k;)6 if (nums[A(i, n)] > median)7 swap(nums, A(i++, n), A(j++, n));8 else if (nums[A(i, n)] < median)9 swap(nums, A(i, n), A(k--, n));10 else11 ++i;12 }13 14 private int A(int i, int n) {15 return (1 + 2 * i) % (n | 1);16 }17 18 19 private int findKthLargest(int[] nums, int k) {20 return quickSelect(nums, 0, nums.length - 1, k);21 }22 23 private int quickSelect(int[] nums, int l, int r, int k) {24 final int pivot = nums[r];25 26 int nextSwapped = l;27 for (int i = l; i < r; ++i)28 if (nums[i] >= pivot)29 swap(nums, nextSwapped++, i);30 swap(nums, nextSwapped, r);31 32 final int count = nextSwapped - l + 1; 33 if (count == k)34 return nums[nextSwapped];35 if (count > k)36 return quickSelect(nums, l, nextSwapped - 1, k);37 return quickSelect(nums, nextSwapped + 1, r, k - count);38 }39 40 private void swap(int[] nums, int i, int j) {41 final int temp = nums[i];42 nums[i] = nums[j];43 nums[j] = temp;44 }45}46