坚持就是胜利!
题目:
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
输入: nums =[0,1,0,3,12]
输出:[1,3,12,0,0]
注意点:
- 将数组前移后,每个数字的索引会变
- 进阶:尽量减少完成的操作次数
标准做法:
双指针想法:使左右指针从头开始,右指针不断右移,左指针在右指针遇到非零的数时,与右指针的数交换后才右移
保证:非零-左指针-零-右指针-未识别
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
n = len(nums)
left = right = 0
while right < n:
if nums[right] != 0:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right += 1
作者:力扣官方题解
链接:https://leetcode.cn/problems/move-zeroes/solutions/489622/yi-dong-ling-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
-
时间复杂度:O(n),其中 n 为序列长度。每个位置至多被遍历两次。
-
空间复杂度:O(1)。只需要常数的空间存放若干变量。
自己的做法:【通过但有点擦边】
先把不为0的数存在其他数组,再加满0【这个算是存了数组了吗】时间复杂度为O(N)
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = []
for x in nums:
if x:
n.append(x)
for i in range(len(nums)):
if i < len(n):
nums[i] = n[i]
else:
nums[i] = 0
1.复杂度高n2
10分钟写一个遇到0直接把所有数往前移动的代码
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = len(nums)
i = 0
while n>0:
if nums[i] == 0:
for j in range(i, len(nums)-1):
nums[j] = nums[j+1]
nums[-1] = 0
else:
i += 1
n -= 1