[Swift]LeetCode280. 摆动排序 $ Wiggle Sort
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10685853.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].
给定一个未排序的数组nums,将其重新排序,使nums[0]<=nums[1]>=nums[2]<=nums[3]…
例如,给定nums=[3,5,2,1,6,4],一个可能的答案是[1,6,2,5,3,4]。
Solution
1 class Solution { 2 func wiggleSort(_ nums:inout [Int]) { 3 if nums.count <= 1 {return } 4 for i in 1..<nums.count 5 { 6 if (i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1]) 7 { 8 nums.swapAt(i,i - 1) 9 } 10 } 11 } 12 }
点击:Playground测试
1 var sol = Solution() 2 var arr:[Int] = [3,5,2,1,6,4] 3 sol.wiggleSort(&arr) 4 print(arr) 5 //Print [3, 5, 1, 6, 2, 4]