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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int len = nums.size();
int one = 0, zero = 0;
for(; zero < len; zero++) {
if(nums[zero]!=0 && one!=zero) {
int temp = nums[zero];
nums[zero] = nums[one];
nums[one] = temp;
one++;
} else if(nums[zero]!=0 && one==zero) {
one++;
}
}
}
};
本文介绍了一种算法解决方案,用于将数组中的所有零元素移动到数组的末尾,同时保持非零元素的相对顺序不变。该方法通过一次遍历实现,并且不需要额外的空间来存储数组元素。
419

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



