Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
Follow up: Could you minimize the total number of operations done?
链接:
https://leetcode.cn/problems/move-zeroes/description/
思路:
设置快慢指针,快指针找到第一个非零元素,慢指针找到第一个零元素,交换位置即可。
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
slow,fast = 0,0
while fast < len(nums):
while nums[slow] !=0 and slow < len(nums)-1:
slow += 1
fast += 1
while nums[fast] == 0 and fast < len(nums)-1:
fast += 1
nums[slow],nums[fast] = nums[fast],nums[slow]
slow += 1
fast += 1