[LeetCode]283. Move Zeroes 解题报告(C++)
题目描述
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.
题目大意
- 给定一个数组. 将所有的
0
移动到后面 - 要求不能改变非零数的相对应的位置关系!!!
- 而且不能使用额外空间.
解题思路
方法1:
- 不满足题目要求. 暴力解法.
- 因为不能改变相对位置. 使用
queue
将所有非零的入队.再出队. - 最后补上0.
代码实现:
/*
我的解法:不满足要求.使用了额外的空间
*/
void moveZeroes1(vector<int>& nums) {
queue<int> q1;
int num = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i]!= 0) {
q1.push(nums[i]);
}
else {
num++;
}
}
int i = 0;
while (q1.size() )
{
nums[i] = q1.front();
q1.pop();
i++;
}
while (num) {
nums[i] = 0;
i++;
num--;
}
}
方法2:
快慢指针
- 快指针找到非零的元素与前面的指针交换位置.
- 然后慢指针也自增
代码实现:
void moveZeroes2(vector<int>& nums) {
for (int i=0,j=0;j<nums.size();j++)
{
if (nums[j]) {
swap(nums[i], nums[j]);
i++;
}
}
}
小结
快慢指针
的方法非常优秀! 要记下来!!!