Leetcode.283 | Move Zeroes(Python)
2021-04-07 07:26
标签:input self copy number strong while 插入 elements put Given an array Example: Note: 利用一个指针指向列表第一个0,寻找之后非零数字与其交换 Leetcode.283 | Move Zeroes(Python) 标签:input self copy number strong while 插入 elements put 原文地址:https://www.cnblogs.com/xm08030623/p/13390349.htmlLeetcode.283 Move Zeroes
nums
, write a function to move all 0
‘s to the end of it while maintaining the relative order of the non-zero elements.Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Solution
移位置零
class Solution:
def moveZeroes(self, nums: list[int]) -> None:
"""
填充,移位,置零
"""
# j指向非0数字将要插入的位置
j = 0
n = len(nums)
for i in range(n):
if nums[i] != 0:
nums[j] = nums[i]
j += 1
for i in range(j, n):
nums[i] = 0
快慢指针
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if not nums:
return nums
zero = 0
n = len(nums)
# zero point first 0
while zero
文章标题:Leetcode.283 | Move Zeroes(Python)
文章链接:http://soscw.com/index.php/essay/72301.html