Leetcode 280. Wiggle sort (oscillating 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] .

Title Tags: Array, Sort

The topic gave us a nums array, let's wiggle sort.

Wiggle Sort attribute: All index is odd number greater than or equal to both sides of the number.

We can understand from another angle: All even index numbers are smaller than the next number, and all odd index numbers are greater than or equal to the next number.

This allows you to traverse the nums, checking each pair of numbers according to the odd even number, and swap them if they do not meet the requirements.

Java Solution:

Runtime beats 60.02%

Completion Date: 09/10/2017

Keywords: Array

Key points: Traverse check each pair of numbers, do not meet the requirements of the swap

1 classSolution2 {3      Public voidWigglesort (int[] nums)4     {5          for(inti=0; i<nums.length; i++)6         {7             //For even index8             if(i% 2 = = 0)9             {   Ten                 //if even index number > next one, swap them One                 if(I+1 < nums.length && Nums[i] > nums[i+1]) A                 { -                     inttemp =Nums[i]; -Nums[i] = nums[i+1]; theNUMS[I+1] =temp; -                 } -             } -             Else //For Odd index +             { -                 //if odd index number < next one, swap them +                 if(I+1 < nums.length && Nums[i] < nums[i+1]) A                 { at                     inttemp =Nums[i]; -Nums[i] = nums[i+1]; -NUMS[I+1] =temp; -                 } -             } -         } in     } -}

Reference: N/A

Leetcode algorithm topic List- leetcode algorithms Questions list

Leetcode 280. Wiggle sort (oscillating 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.