剛開始刷LeetCode,編程能力暫處小學水平,記錄下心得,借鑑 https://blog.csdn.net/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++]);
}
}
}
};