【题目】
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.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
给定一个数组,将数组中所有的“0”移到数组的末尾,保持数组中其他数字相对位置不变。
【解析】
思路一:
字面意思,对数组进行一次遍历,删除元素0,在数组末尾添加0。
程序如下:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
i = 0
while n:
if nums[i] == 0:
nums.append(0)
del nums[i]
i -= 1
i += 1
n -= 1
运用Python后,感觉粗暴的算法也能实现了!
思路二:
遍历一遍数组,如果该元素为零则不进行操作,如果该元素不为零则从数组的第一个元素开始进行覆盖,并且计数,最后将检索到的0添加到数组最后。
C++程序如下:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j = 0;
// move all the nonzero elements advance
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[j++] = nums[i];
}
}
for (;j < nums.size(); j++) {
nums[j] = 0;
}
}
};
【关于bug】
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)):
if nums[i] == 0:
nums.append(0)
del nums[i]
该程序出现的问题是删除了nums[i]以后,nums[i:]都会向前移动,因此标号i的位置会改变。因此在完成删除动作以后,应当加上语句使得i指向需要检索的下一个元素。