Given an integer array nums
, move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]
Example 2:
Input: nums = [0] Output: [0]
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
Follow up: Could you minimize the total number of operations done?
这个题目偏简单(委婉的说法,实则简单到过分),本来不想发的,但考虑到自己双指针用的不太熟练,还是发个文章记录一下。
由于自己双指针用的不多,首先考虑的是一次遍历,个人觉得我这个方法其实不考虑使用双指针的话,还是该题比较不错的一个算法,时间复杂度为o(n),空间复杂度为o(1)。
考虑到往后放的元素都是0,我们可以在第一次遍历时,就把每个元素放在他该放的位置上,然后在后面进行补0,代码如下:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int count = 0;
for(int i = 0;i < nums.size();i++)
{
if(nums[i] == 0)
count++;
else
nums[i - count] = nums[i];
}
for(int i = nums.size() - count;i < nums.size();i++)
{
nums[i] = 0;
}
}
};
接下来是双指针的方法,其实上面的方法和双指针有着异曲同工之妙,如第10行的代码中的i-count和i就可以看作两个指针变量。下面给出双指针的代码:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j = 0;
for(int i = 0;i < nums.size();i++)
{
if(nums[i] != 0)
{
nums[j] = nums[i];
j++;
}
}
for(int i = j;i < nums.size();i++)
{
nums[i] = 0;
}
}
};
我认为这两种方法是基本相似的,只要找准了每个元素移动后的位置,双指针的优势在于元素移动先后的始末位置都很清晰,如该题,移动前的位置是i,移动后的位置是j,比第一种方法要清晰许多。