283. Move Zeroes
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:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
题意:
给定数组nums,写一个函数来移动所有的元素0到数组的末尾,同时保持非零元素在数组中的相对顺序。
注意:
1. 你必须在本数组空间内完成,不能复制数组。
2. 减少操作的总数。
方法一:
思路:
利用vector的erase()方法删除指定位置的元素,其中erase()方法的参数是位置的迭代器。
例如:vec.erase(vec.begin()+2);//删除第3个元素
void moveZeroes(vector<int>& nums) {
int n=nums.size();
for (int i=0;i<nums.size();i++)
{
if(nums[i]==0) {
nums.erase(nums.begin()+i);//删除第i个为0的元素
i=-1;//重置下次迭代的起始点从数组的首元素开始
}
}
int m=nums.size();
for (int i=0;i<(n-m);i++)
{
nums.push_back(0);//填充删掉的0元素在数组末尾
}
}
方法二:
思路:
利用双指针,一前一后遍历nums数组,right在前,left在后。如果right所指元素非0且left为0则交换,left所指元素非零的时候向前移动,right所指元素不管是否是0都向前移动(因为当不为0时进行交换后变为0,为0直接移动)。代码如下:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
int left = 0, right = 0;
while (right < n){
if (nums[right] != 0 && nums[left] == 0){
swap(nums[left], nums[right]);
left++;
}
if (nums[left] != 0)
left++;
right++;
}
}
方法三:
思路:
和方法二类似,利用双指针,一前一后遍历nums数组,right在前,left在后。此代码利用一个巧妙的地方就是刚刚开始left==right,只要right所指元素不为0,left和right同时向前移动,如果right所指元素为0,则right向前移动,left记录为0元素的位置,当right所指元素不为0时直接覆盖left所指元素并且left向后移动,最后补全后面缺省的元素0。代码如下:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
int left = 0, right = 0;
while (right < n){
if (nums[right]){
nums[left] = nums[right];
left++;
}
right++;
}
while (left < n)
nums[left++] = 0;
}