★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-aermoxpl-kx.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.git
Example:github
Input: Output: [0,1,0,3,12][1,3,12,0,0]
Note:數組
給定一個數組 nums
,編寫一個函數將全部 0
移動到數組的末尾,同時保持非零元素的相對順序。微信
示例:app
輸入: 輸出: [0,1,0,3,12][1,3,12,0,0]
說明:函數
16msthis
1 class Solution { 2 func moveZeroes(_ nums: inout [Int]) { 3 //0要後移,反意是非0元素前移。 4 if nums == nil || nums.count == 0 5 { 6 return 7 } 8 //記錄非0元素開始位置 9 var j:Int = 0 10 for i in 0..<nums.count 11 { 12 if nums[i] != 0 13 { 14 nums[j] = nums[i] 15 j += 1 16 } 17 } 18 while(j < nums.count) 19 { 20 nums[j] = 0 21 j += 1 22 } 23 } 24 }
16msspa
1 class Solution { 2 func moveZeroes(_ nums: inout [Int]) { 3 var firstPointer = 0 4 var secondPointer = 0 5 6 while secondPointer < nums.count { 7 if nums[firstPointer] == 0 { 8 if nums[secondPointer] != 0 { 9 swap(&nums, firstPointer, secondPointer) 10 } else { 11 secondPointer += 1 12 } 13 } else { 14 secondPointer += 1 15 firstPointer += 1 16 } 17 } 18 } 19 20 func swap(_ nums: inout [Int], _ firstIndex: Int, _ secondIndex: Int) { 21 var temp = nums[firstIndex] 22 nums[firstIndex] = nums[secondIndex] 23 nums[secondIndex] = temp 24 } 25 }
16mscode
1 class Solution { 2 func moveZeroes(_ nums: inout [Int]) { 3 var index1 = 0 4 var index2 = nums.count 5 while index1 <= index2 - 1 { 6 if nums[index1] == 0 { 7 for _ in 0..<(index2-index1) { 8 index2 -= 1 9 if nums[index2] != 0 { 10 nums.remove(at: index1) 11 nums.append(0) 12 break; 13 } 14 } 15 }else { 16 index1 += 1 17 } 18 } 19 } 20 }
20ms
1 class Solution { 2 func moveZeroes(_ nums: inout [Int]) { 3 var removedCount = 0 4 for (idx, val) in nums.enumerated() { 5 if val == 0 { 6 nums.remove(at: idx-removedCount) 7 removedCount += 1 8 nums.append(0) 9 } 10 } 11 } 12 }