给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/move-zeroes
python
# 移动零,其他元素相对位置不变
class Solution:
def moveZeroes(self, nums: [int]):
"""
双指针法, 时间O(n), 空间O(1)
:param nums:
:return:
"""
slow, fast = 0, 0
n = len(nums)
while fast < n:
if nums[fast] != 0:
nums[slow], nums[fast] = nums[fast], nums[slow]
slow += 1
fast += 1
def moveZeroes1(self, nums: [int]):
"""
冒泡版暴力遍历,时间O(n^2), 空间O(1)
:param nums:
:return:
"""
n = len(nums)
for i in range(0, n):
for j in range(0, n-i-1):
if nums[j] == 0:
nums[j], nums[j+1] = nums[j+1], nums[j]
if __name__ == "__main__":
nums1 = [1]
nums2 = [0,0,2,4,5,6,3,4,0,0,56]
nums3 = [1,0,2,4,0,6,0,4,0,0,56]
test = Solution()
test.moveZeroes(nums1)
test.moveZeroes(nums2)
test.moveZeroes1(nums3)
print(nums1, nums2, nums3, end=' ')
golang
package main
import "fmt"
func main() {
var nums = []int{0, 0, 2, 4, 5, 6, 3, 4, 0, 0, 56}
moveZeroes(nums)
fmt.Println(nums)
}
// 双指针法
func moveZeroes(nums []int) {
var slow int = 0
var temp int
var n int = len(nums)
for fast := 0; fast < n; fast++ {
if nums[fast] != 0 {
temp = nums[fast]
nums[fast] = nums[slow]
nums[slow] = temp
slow++
}
}
}
// 暴力法-冒泡版
func moveZeroes1(nums []int) {
n := len(nums)
var temp int
for i, _ := range nums {
for j := 0; j < n-1-i; j++ {
if nums[j] == 0 {
temp = nums[j]
nums[j] = nums[j+1]
nums[j+1] = temp
}
}
}
}