0
点赞
收藏
分享

微信扫一扫

LeetCode刷题——283. 移动零

飞鸟不急 2022-07-14 阅读 135


题目

LeetCode刷题——283. 移动零_leetcode

解法

解法一

题目要求只能原地操作。

简单的,用两个循环,一个遍历所有元素,找到零元素;另一个遍历非零元素,交换。

class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)):
if nums[i] != 0:
continue
for j in range(i+1,len(nums)):
if nums[j] != 0:
nums[i] = nums[j]
nums[j] = 0
break

return

LeetCode刷题——283. 移动零_leetcode_02


虽然通过了,但是消耗排名不太理想。那么如何优化这个解法呢。

解法二

解法一用了两个循环,仔细思考一下,是不是一个循环也可以。只需要一个额外的变量来记录非零元素的位置。

class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
k = 0 # num[0...k)存放的是非零元素
for i in range(len(nums)):
if nums[i] != 0:
nums[k] = nums[i]
k += 1

# 剩下的[k,size) 都是0
for i in range(k,len(nums)):
nums[i] = 0

return

LeetCode刷题——283. 移动零_leetcode_03


举报

相关推荐

0 条评论