Swap based on mod 2 / T : O(N), S : O(1)


  • 0
    J
    public void wiggleSort(int[] nums) {
            for(int i = 0; i < nums.length - 1; i++){
                if(i%2 == 0 && nums[i] > nums[i+1]){
                    swap(nums, i, i+1);
                }
                else if(i%2 == 1 && nums[i] < nums[i+1]){
                    swap(nums, i, i+1);
                }
            }
        }
        
        public void swap(int[] nums, int i, int j){
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    

Log in to reply
 

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