LeetCode——移动零
题目描述:
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/move-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
解法一:
我们使用python语言的特殊方法:
使用count函数计算nums中0的个数,然后将nums中的每个0元素remove掉,再使用append函数将0元素添加到nums的末尾。
解法二:
双指针法:定义一个left和一个right;
left指向处理完的一段的末尾;right指向未处理一段的开头。
当right指向的元素不为0时,我们交换left和right指向的元素,让非零元素往前移动。
解法一python代码:
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(nums.count(0)):
nums.remove(0)
nums.append(0)
return nums
解法二python代码:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
left, right = 0, 0
while right < len(nums):
if nums[right]:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right += 1
return nums