class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(nums.count(0)):
nums.remove(0)
nums.append(0)
数一数有几个0就给它抠了然后末尾补上。思路很好,就是有点慢。
remove的时间复杂度是O(n)
下面这个同理,稍快一些
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
count = nums.count(0)
if count == 0 or count == len(nums):
return
nums[:] = [num for num in nums if num!=0] + [0]*count
标准答案是用快慢指针,快指针去探路,遇到不是零的就和慢指针交换位置,交换完慢指针加一。
把非0数存下来,把左边的0全扔到右边去,比较抽象
这么理解,一个指针(快),每遇到一个非零数,都和它左侧最远的那个0交换位置,想象有两个数组。
下面是Java代码
class Solution {
public void moveZeroes(int[] nums) {
if (nums.length == 1) {
return;
}
int left = 0;
int right = 0;
//右快左慢
while (right < nums.length) {
if (nums[right] != 0) {
int temp = nums[left]; //左右交换
nums[left] = nums[right];
nums[right] = temp;
left++;
}
right++;
}
}
}