283. Move Zeroes
Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
解题思路:
双指针法,慢指针停留在 0 ,快指针寻找非零元素进行交换。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
i, j = 0, 0
while j < len(nums):
if nums[i] <> 0 and nums[j] <> 0:
i += 1
elif nums[i] == 0 and nums[j] <> 0:
tt = nums[j]
nums[j] = nums[i]
nums[i] = tt
i += 1
j += 1
return nums
请多多指教。
文章标题:283. Move Zeroes
本文作者:顺强
发布时间:2019-09-02, 23:59:00
原始链接:http://shunqiang.ml/leetcode-283-move-zeros/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。