移动零
LeetCode283. 移动零
题目描述
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
1
2
|
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
|
示例 2:
1
2
|
输入: nums = [0]
输出: [0]
|
思路
题目描述
移除数组元素,考虑使用双指针法。慢指针的移动条件应为nums[fastIndex] != 0
,
注意
由于是将0
移到数组末尾,并非是完全移除,所有当快指针找到不为0
的数时,慢指针和快指针的值应该交换。
代码
Go
1
2
3
4
5
6
7
8
9
|
func moveZeroes(nums []int) {
slowIndex := 0
for fastIndex := 0; fastIndex < len(nums); fastIndex++ {
if nums[fastIndex] != 0 {
nums[slowIndex], nums[fastIndex] = nums[fastIndex], nums[slowIndex]
slowIndex += 1
}
}
}
|
Link
GitHub