280.Wiggle Sort

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] .

Links: http://leetcode.com/problems/wiggle-sort/


Wiggle a sorted array. Follow the test instructions to write it. You can also simplify and learn more about Stefan's code.

Time Complexity-o (n), Space complexity-o (1)

 Public classSolution { Public voidWigglesort (int[] nums) {         for(inti = 1; i < nums.length; i++) {            if(i% 2 = = 1) {                if(Nums[i] < nums[i-1]) {swap (nums, i); }            } Else {                if(I! = 0 && nums[i] > Nums[i-1]) {swap (nums, i); }            }        }    }        Private voidSwapint[] Nums,inti) {intTMP = Nums[i-1]; Nums[i-1] =Nums[i]; Nums[i]=tmp; }}






280.Wiggle Sort

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.