80 - 移动零
题目
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12] 输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
解答
要做两件事:
把非零元素挪动到前面
把后面的元素全部变成0
题解是保留了一个指针,记录最后的那个非零元素位置。
Runtime: 60 ms, faster than 83.60% of JavaScript online submissions for Move Zeroes.
Memory Usage: 35.8 MB, less than 36.17% of JavaScript online submissions for Move Zeroes.
题解里面的做法:
就相当于
因为这个放在后面的++
,是表达式结束后才+的。
不过感觉难以理解,就拿出来了。
Runtime: 64 ms, faster than 77.91% of Go online submissions for Move Zeroes.
Memory Usage: 7.9 MB, less than 60.00% of Go online submissions for Move Zeroes.
一口气解决
还是双指针,如果不是0,就交换一下
我一开始想法也这样,咋就只能写出死循环呢😂😂
Runtime: 60 ms, faster than 83.60% of JavaScript online submissions for Move Zeroes.
Memory Usage: 36.5 MB, less than 8.51% of JavaScript online submissions for Move Zeroes.
Runtime: 60 ms, faster than 97.09% of Go online submissions for Move Zeroes.
Memory Usage: 7.7 MB, less than 100.00% of Go online submissions for Move Zeroes.
go好像没法在for里面定义两个变量😂
Last updated
Was this helpful?