LeetCode刷题(Move Zeroes)-小增笔记
今天刷的题不难,具体题目如下:
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.
解答如下
方法一
用vector<int> 新建一个数组nonElements,遍历nums中所有元素,并将其中的非零元素全部压栈push_back(不能直接赋值,直接赋值会报错)到新数组中,然后,遍历nonElements中所有元素,并将nonElements的所有元素直接覆盖nums中对应的元素,最后在将nums中未被覆盖的元素置零。代码如下:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
vector<int> nonElements;
for(int i=0; i<nums.size(); i++)
if(nums[i])
nonElements.push_back(nums[i]);
for(int i=0; i<nonElements.size(); i++)
nums[i]=nonElements[i];
for(int i=nonElements.size(); i<nums.size(); i++)
nums[i]=0;
}
};
提交后的结果如下,很显然此时代码的时间复杂度为O(n)(存在循环次数为n的for循环),空间复杂度也为O(n)(存在辅助数组nonElements),因此仍需继续优化代码。
方法二
用i去遍历nums数组,并用k去记录nums数组中的非零元素,并进行相应的覆盖,未覆盖的元素置零。该方法时间复杂度未变,因不用辅助数据,所以空间复杂度为O(1).
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int k = 0;//nums中,[0...k)的元素均为非0元素
for(int i=0; i<nums.size(); i++)
if(nums[i])
nums[k++]=nums[i];
for(int i=k; i<nums.size(); i++)
nums[i]=0;//[k...nums.size()]的元素均为0元素
}
};
提交后的结果如下:
方法三
遇到非零元素就交换,最终得到的结果就是想要的结果。该方法时间复杂度未变,因不用辅助数据,所以空间复杂度为O(1).
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int k = 0;
for(int i=0; i<nums.size(); i++)//遇到非零元素就交换,最终可得到想要的结果
if(nums[i])
swap(nums[k++], nums[i]);
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。