Title description
Given an array nums
, write a function to move everything 0
to the end of the array while maintaining the relative order of non-zero elements.
Example:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
Description :
- You must operate on the original array, and cannot copy additional arrays.
- Minimize the number of operations.
Solution 1: Double pointer, the first 0 is exchanged with the first non-zero after it
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int len = nums.size();
int first0 = -1; //无效的初始index
for (int i = 0; i < len; ++i)
if (0 == nums[i]) {
if (first0 < 0) //寻找第一个0的index
first0 = i;
} else if (first0 >= 0) { //第一个0已找到,且找到第一个0后面第一个非0元素
swap(nums[first0], nums[i]); //把第一个0换成非0元素
i = first0; //从刚才第一个0后面重新找新的第一个0
first0 = -1;
}
}
};
Solution 2: Double pointer, j records the index where the non-zero element should be, i finds the non-zero element; there is a repeated operation of self-exchange
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int len = nums.size();
int j = 0; //遇非0元素自加
for (int i = 0; i < len; ++i)
if (nums[i])
swap(nums[j++], nums[i]); //把非0元素全部换到前面
}
};
Solution 3: Optimization of solution 2 to avoid exchanging values with yourself
//如果元素不为0,i,j跟着一起动。如果元素为零,j记录为零的下标
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int len = nums.size();
int j = 0;
for (int i = 0; i < len; ++i)
if (nums[i]) {
if (i > j) {
nums[j] = nums[i];
nums[i] = 0;
}
++j;
}
}
};