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
my: 113ms..... - - !
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
for(int i = 0; i < n; i++)
{
if(nums[i] == 0)
{
for(int j = n-1; j > i; j--)
{
if(nums[j] != 0)
swap(nums[i], nums[j]);
}
}
}
}
};
better : 13 ms........ 这里不用两次迭代,快很多。
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
int j = 0;
for(int i = 0; i < n; i++)
{
if(nums[i] != 0)
nums[j++] = nums[i];
}
for(;j < n; j++)
nums[j] = 0;
}
};
本文介绍了一种高效的方法来解决将数组中所有零元素移动到末尾的问题,同时保持非零元素的相对顺序不变。通过两种不同的实现方式对比,展示了如何减少操作次数并提高算法效率。
400

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



