我想知道为什么我对这个 LeetCode“移动零点”问题的解决方案比大多数其他提交都慢。有没有更好的方法来解决这个问题以使其更快?
题目如下:
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. You must do this in-place without making a copy of the array.Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
这是我的解决方案:
func moveZeroes(_ nums: inout [Int]) {
var index = 0
for (i,n) in nums.enumerated()
{
if n != 0
{
nums[index] = n
index += 1
}
}
while index < nums.count
{
nums[index] = 0
index += 1
}
}
LeetCode 给了我这些统计数据:
Runtime: 52 ms, faster than 40.50% of Swift online submissions for Move Zeroes.
Memory Usage: 19.4 MB, less than 13.33% of Swift online submissions for Move Zeroes.
编辑 1:
如果我按如下方式解决问题,它不会移动末尾的零,
编辑 2:
最佳答案
这是适合您的 36 毫秒就地解决方案:
class Solution {
func moveZeroes(_ nums: inout [Int]) {
if nums.count < 2 {
return
}
var j = 0
while j < nums.count, nums[j] != 0 {
j += 1
}
if j < nums.count - 1 {
for i in j+1..<nums.count {
if nums[i] != 0 {
nums.swapAt(i, j)
j += 1
}
}
}
}
}
关于arrays - 将零移动到数组编程练习末尾的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54871337/