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].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
void moveZeroes(int* nums, int numsSize)
{
int k = 0;
for(int i = 0;i < numsSize;i++)
{
if(nums[i] != 0)
nums[k++] = nums[i];
}
for(;k<numsSize;k++)
nums[k] = 0;
}
2021.04.23更新
周五下班头昏脑涨,昏昏沉沉写出了如下代码,感觉自己越来越菜了:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int nonzero = 0;
int size = nums.size();
for(int i = 0;i < size;i++)
{
//统计非0元素个数
if(nums[i] != 0)
nonzero += 1;
}
int start = 0,k = 0;
while(k < size)
{
if(nums[k] != 0)
{
nums[start++] = nums[k];
}
k++;
}
int i = 0;
while(i < size - nonzero)
{
nums[nonzero + i++] = 0;
}
}
};
运行效率居然击败90%的人
Runtime: 4 ms, faster than 90.12% of C++ online submissions for Move Zeroes.
Memory Usage: 9 MB, less than 56.46% of C++ online submissions for Move Zeroes.
看了自己两年前写的代码:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int k = 0,size = nums.size();
for(int i = 0;i < size;i++)
{
if(nums[i] != 0)
nums[k++] = nums[i];
}
for(;k < size;k++)
nums[k] = 0;
}
};
效率击败100%
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Move Zeroes.
Memory Usage: 8.9 MB, less than 83.55% of C++ online submissions for Move Zeroes.