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:
Input:[0,1,0,3,12]Output:[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的元素放到数组的末尾。本题是一道常规题目,核心思想是记录数组中不为零的元素索引,在遍历数组的过程中维护此索引,直到遍历到数组的结尾,具体如下:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int i = 0;
for(int j = 0; j < nums.size(); j++)
{
if (nums[j] != 0)
nums[i++] = nums[j];
}
for( ; i < nums.size(); i++)
nums[i] = 0;
}
};
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int tmp = 0, j = 0;
for(int i = 0, end = nums.size(); i < end; i++)
{
tmp = nums[i];
if(tmp != 0)
{
nums[i] = nums[j];
nums[j++] = tmp;
}
}
}
};
本文介绍了一种有效的算法,用于将数组中的所有零元素移动到数组的末尾,同时保持非零元素的相对顺序不变。通过双指针技术,该算法在原地操作,避免了额外的空间开销,并最小化了操作次数。

233

被折叠的 条评论
为什么被折叠?



