[LeetCode] 283. Move Zeroes
Description
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.
Example:
Input: [0,1,0,3,12]
Output: [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.
Analyse
将一个数组里所有的0移到非0值得右边,不打乱非0值得顺序
关键在于in-place,不能申请额外的内存空间
遍历vector,用非0值覆盖0值就行了,用一个index记录当前写到vector的哪个位置了
void moveZeroes(vector<int>& nums) {
int len = nums.size();
int current_not_zero_index = 0;
int nonzero_count = 0;
for (int i = 0; i < len; i++) {
if (nums[i] == 0) {
continue;
} else {
++nonzero_count;
nums[current_not_zero_index++] = nums[i];
}
}
for (int j = nonzero_count; j < len; j++) {
nums[j] = 0;
}
}
下面的代码是Leetcode上最快的解法,使用了remove来移除vector中的0值
void moveZeroes(vector<int>& nums) {
ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
int n1 = nums.size();
vector <int>::iterator pos;
pos = remove (nums.begin(), nums.end() , 0); // 指向未被remove元素的后面一个元素的
for(auto i = pos; i != nums.end(); ++i)
*i = 0;
}
下面介绍remove()
,功能和我上面写的代码差不多
template <class ForwardIterator, class T>
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val)
{
ForwardIterator result = first;
while (first!=last) {
if (!(*first == val)) { // 只有值不为val的元素才会被添加到result中
*result = *first;
++result;
}
++first;
}
return result;
}
remove的返回值是 指向最后一个未被remove元素的后面一个元素的迭代器,在这里是指向第一个0的迭代器
An iterator to the element that follows the last element not removed.
The range between first and this iterator includes all the elements in the sequence that do not compare equal to val.
举例说明remove函数的处理过程
输入: [0,1,0,3,12]
[0,1,0,3,12] // 遍历到input[0]
[1,1,0,3,12] // 遍历到input[1]
[1,1,0,3,12] // 遍历到input[2]
[1,3,0,3,12] // 遍历到input[3]
[1,3,12,3,12] // 遍历到input[4]
remove后输出:[1,3,12,3,12]