[Swift]LeetCode280. 擺動排序 $ Wiggle Sort

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-ohtnobuw-ky.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

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

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


給定一個未排序的數組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測試spa

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]
相關文章
相關標籤/搜索