**题目:**给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
C++:
1、常规思路:
先遍历一次,记录当前遍历到的非零元素的个数(若为第n个非0的元素,就将该非零至于数组中下标为n - 1的位置);在非零元素遍历完毕后,得到flag个非零元素。从第flag + 1个元素开始,剩余的元素全部置0,即为所求结果。
#include<iostream>
#include<vector>
using namespace std;
class Solution
{
public:
void zero(vector<int>& nums)
{
int n = 0;
for (int i = 0; i < nums.size() - 1; i++)
{
if (nums[i] != 0) // 若不为零,则i和n-1交换
{
n++;
nums[n - 1] = nums[i];
}
}
if (n > 0)
{
for (int j = n; j < nums.size(); j++)
nums[j] == 0;
}
}
};
int main()
{
solution S;
vector<int> nums = {2,5,8,0,1,6,0,7,0};
S.zero(nums);
return 0;
}
2、双指针
快慢指针,快指针向前移动,若不为0,则和慢指针交换,若为0,继续向前。
class solution
{
public:
void zero(vector<int>& nums)
{
int n = nums.size(); int left = 0; int right = 0;
while (right < n)
{
if (nums[right] != 0)
{
swap(nums[left], nums[right]);
left++;
}
right++;
}
}
};
python:
思路:双指针
left指针指向非0的最后一位,right指向0的最后一位,每次判断right指向的是否为0,若为0则后移一位,若非0则交换left和right,让left向后移动一位。
from typing import List
class Solution:
def moveZeroes(self, nums: List[int]):
n = len(nums)
left = right = 0
while right < n:
if nums[right] != 0:
temp = nums[right]
nums[right] = nums[left]
nums[left] = temp
left += 1
right += 1
if __name__== "__main__":
nums = [0,1,0,3,12]
res = Solution().moveZeroes(nums)
print(nums)