Leetcode - Check If a Number Is Majority Element in a Sorted Array
Leetcode - Rotate List

Leetcode - Wiggle Sort

violet posted @ Mar 24, 2020 04:02:30 AM in 算法 with tags Algorithm Golang array Sort , 60 阅读

https://leetcode.com/problems/wiggle-sort/

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

Example:

Input: nums = [3,5,2,1,6,4]
Output: One possible answer is [3,5,1,6,2,4]

 

func wiggleSort(nums []int)  {
    for i := 0; i < len(nums); i++ {
        if i%2 == 1 {
            if nums[i-1] > nums[i] {
                nums[i-1], nums[i] = nums[i], nums[i-1]
            } 
        } else {
            if i != 0 && nums[i-1] < nums[i] {
                nums[i-1], nums[i] = nums[i], nums[i-1]
            }
        }
    }
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter