LeetCode 1-3:283 移动零
我的github地址如下,会经常更新,欢迎star:
https://github.com/guobing21/leetcode
1 题目
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
2 说明
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
Related Topics 数组 双指针
3 解答
1 解答成功: 执行耗时:40 ms,击败了84.05% 的Python3用户 内存消耗:14.3 MB,击败了7.41% 的Python3用户
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
if not nums:
return 0
# 两个指针i和j
j = 0
for i in range(len(nums)):
# 当前元素!=0,就把其交换到左边,等于0的交换到右边
if nums[i]:
nums[j],nums[i] = nums[i],nums[j]
j += 1
2 解答成功: 执行耗时:40 ms,击败了84.05% 的Python3用户 内存消耗:14.3 MB,击败了7.41% 的Python3用户
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[j] = nums[i]
if i != j:
nums[i] = 0
j += 1
3 解答成功: 执行耗时:48 ms,击败了51.89% 的Python3用户 内存消耗:14.4 MB,击败了7.41% 的Python3用户
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
counts_zero = 0
for i in range(len(nums)-1, -1, -1):
if nums[i] == 0:
nums.pop(i)
counts_zero += 1
nums += [0]*counts_zero
4 解答成功: 执行耗时:48 ms,击败了51.89% 的Python3用户 内存消耗:14.1 MB,击败了7.41% 的Python3用户
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
counts_zero = 0
i = len(nums) - 1
while i >= 0:
if nums[i] == 0:
nums.pop(i)
counts_zero += 1
i -= 1
nums += [0] * counts_zero
5 解答成功: 执行耗时:96 ms,击败了24.26% 的Python3用户 内存消耗:14.4 MB,击败了7.41% 的Python3用户
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
counts_zero = 0
i = -len(nums)
while i < 0:
if nums[i] == 0:
nums.remove(0)
counts_zero += 1
i += 1
nums += [0]*counts_zero
6 解答成功: 执行耗时:108 ms,击败了20.58% 的Python3用户 内存消耗:14.2 MB,击败了7.41% 的Python3用户
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
counts_zero = 0
for i in range(-len(nums), 0, 1):
if nums[i] == 0:
nums.remove(0)
counts_zero += 1
nums += [0]*counts_zero
7 解答成功: 执行耗时:108 ms,击败了20.58% 的Python3用户 内存消耗:14.4 MB,击败了7.41% 的Python3用户
缺点是时空复杂度都高,因为对列表使用了remove,因此不推荐
时间复杂度O(n^2)
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in nums[:]:
if i == 0:
nums.append(0)
nums.remove(0)