记录一个下标,对原数组进行遍历,当非0时,将该数置于该下标内,并将下标值+1
最终从下标到数组尾全部置0.
/**
* @author johnsondu
* @problem Move Zeroes
* @url https://leetcode.com/problems/move-zeroes/
* @timeComlexity O(n)
* @spaceComplexity O(1)
* @strategy See code.
*/
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int len = nums.size();
int idx = 0;
for(int i = 0; i < len; i ++)
{
if(nums[i]) {
nums[idx ++] = nums[i];
}
}
for(int i = idx; i < len; i ++)
nums[i] = 0;
}
};
本文介绍了一种有效的算法,用于将数组中的所有零元素移动到数组的末尾,同时保持非零元素的相对顺序不变。该算法仅使用常数级额外空间,时间复杂度为O(n)。
391

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



