Description:
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:
Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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进行后置而不改变其他数字原有的次序。由于本题要求在原数组上操作并且不通过复制整个数组,因此我们可以用排序的方法来做。
在这里用冒泡排序的思想,从左到右依次读取数组,如果当前的数为0,则与邻近的下一个非零的数进行交换,直到交换到最后一个位置,那么这个算法时间复杂度为O(n^2)。为了再进一步提高时间效率,可以用空间换时间,可以定义一个辅助变量来记录0的位置,从左往右读取数组,如果当前的数不为0且位置比0的位置后,那么当前的数和0的位置进行交换。0的位置则继续推进,直到把所有的数都进行交换。该改进算法的时间复杂度为O(n)。
下面是使用C++的实现过程:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int zero_idx = 0;
for (int i=0; i<nums.size(); i++) {
if (nums[i]!=0) {
if (i>zero_idx) {
swap(nums[i], nums[zero_idx]);
}
zero_idx++;
}
}
}
};