Leetcode 280. Wiggle Sort C #

Source: Internet
Author: User

Given an unsorted array nums , reorder it in-place such nums[0] <= nums[1] >= nums[2] <= nums[3]... .

For example, given nums = [3, 5, 2, 1, 6, 4] , one possible answer are [1, 6, 2, 5, 3, 4] .

Solution:

Loop through, when odd index num should is greater then the previous num;

When even index num should is smaller then the previous num;

So if even index NUM was greater then the previous NUM then it must was greater then the previous of previous Num too Ly swap once.

1  Public classSolution {2      Public voidWigglesort (int[] nums) {3         intL =Nums. Length;4          for(intI=1; i<l;i++)5         {6             if(i%2==1)7             {8                 if(nums[i]<nums[i-1])9                 {Ten Swap (Nums, i); One                 } A             } -             Else -             { the                 if(nums[i]>nums[i-1]) -                 { - Swap (Nums, i); -                 } +             } -         } +     } A      Public voidSwap (int[] Nums,inti) at     { -         inttemp = nums[i-1]; -nums[i-1]=Nums[i]; -Nums[i] =temp; -     } -}

Leetcode 280. Wiggle Sort C #

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.