O(n) time O(n) space solution


  • -12
    A
    public class Solution {
        public void wiggleSort(int[] nums) {
            if (nums.length == 0 || nums.length == 1)
                return;
            Arrays.sort(nums);
            int[] res = new int[nums.length];
            int mid = nums.length/2;
            if (nums.length % 2 != 0)
                mid++;
            int lo = mid - 1;
            int hi = nums.length - 1;
            for (int i = 0; i < nums.length; i++) {
                if (i % 2 == 0) {
                    res[i] = nums[lo];
                    lo--;
                } else {
                    res[i] = nums[hi];
                    hi--;
                }
            }
            for (int i = 0; i < nums.length; i++) {
                nums[i] = res[i];
            }
        }
    }

  • 4
    0

    this is not in O(n) time because the Arrays.sort(nums); takes nlogn time.


  • 0
    L

    nums={4,5,5,5,5,6} your answer is {5,6,5,6,5,5,4 } expected is 5,6,5,6,4,5


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.