[Swift]LeetCode283. 移动零 | Move Zeroes
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9756870.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.
Example:
[0,1,0,3,12]
[1,3,12,0,0]
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
[0,1,0,3,12]
[1,3,12,0,0]
说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
16ms
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 }
16ms
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 }
16ms
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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了