刚开始刷LeetCode,编程能力暂处小学水平,记录下心得,借鉴 https://blog.youkuaiyun.com/biezhihua/article/details/79614021
题目描述
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入:[0,1,0,3,12]
输出:[1,3,12,0,0]
说明
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
解法思路一
对于这种需要在原数组上操作,且考虑到尽量少地减少时间复杂度,也就是减少0之外的数字移动的次数,可以考虑到使用两个指针来进行操作。
curIndex从后向前遍历直到0的位置,lastIndex与curIndex之间的数字向前移动一位,将lastIndex位置赋0,然后将lastIndex前移一位。
class Solution {
public:
void moveZeroes(vector<int>& nums) {
if(nums.empty()){
return ;
}
int curIndex=nums.size()-1;
int lastIndex=nums.size()-1;
int count = 0;
while(curIndex>=0){
if(nums[curIndex] == 0){
count = lastIndex-curIndex;
for(int i=0;i<count;i++){
nums[curIndex+i] = nums[curIndex+i+1];
}
nums[lastIndex] = 0;
lastIndex--;
}
curIndex--;
}
}
};
思路二
同样基于俩个指针的方法用替换法in-place来做,一个不停的向后扫,找到非零位置,然后和前面那个指针交换位置即可,很巧妙的方法。
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++]);
}
}
}
};