C# O(n) inplace with comments


  • 1
    Y
    public class Solution {
        public void WiggleSort(int[] nums) {
            for(int i=1;i<nums.Length;i+=2)
            {
                //swap i with num[i-1], then num[i-1] will less than num[i]
                if(nums[i]<nums[i-1])
                    swap(nums,i,i-1);
                //num[i-1] is less than num[i] and num[i] is less than num[i+1], so num[i+1] will be larger than num[i-1]
                if(i<nums.Length-1&&nums[i]<nums[i+1])
                    swap(nums,i,i+1);
            }
        }
        private 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.