Given an array , write a function to move all 's to the end of it while maintaining the relative order of the non-zero elements. Example: Note:
| 给定一个数组 ,编写一个函数将所有 移动到数组的末尾,同时保持非零元素的相对顺序。 示例: 说明:
|
思路:
第一种:i和j指针同时从前往后扫,i表示不为0 的元素,j指向0元素。当i指向的元素不为0时,nums[i]和nums[j]交换。
class Solution {
public:
void moveZeroes(vector<int>& nums) {
for(int i=0,j=0;i<nums.size();++i)
if(nums[i]) swap(nums[i],nums[j++]);
}
};
第二种:将不为0 的元素从前往后赋值,另外一个变量统计0元素的个数,然后将后面 元素全部 置为0.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int k=0,n=nums.size();
for(int i=0;i<n;++i)
if(nums[i]) nums[k++]=nums[i];
for(int i=n-1;i>k-1;--i) nums[i]=0;
}
};