作者 github链接: github链接
力扣第283题
类型:数组题
题目:
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例1
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]
示例2
输入: nums = [0]
输出: [0]
解题思路
思路提醒:双指针(快指针和慢指针)
思路细节:
- 定义两个指针,例如fast和slow
- 将两个指针都置于数组开头,也就是令
fast = 0,slow = 0
- 快指针依次遍历整个数组,
什么时候要采取操作呢?
- 当快指针一旦遇到
不等于0
的数字时候,这时要采取操作:将慢指针指向位置的数值和快指针指向位置的数值交换
- 交换位置之后,将慢指针的位置向下一个位置+1
- 重复
4~5
直到遍历完成
c++版
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
int fast = 0,slow = 0;
for(int i = 0;i<n;i++){
if(nums[i]!=0){
swap(nums[fast], nums[slow]);
slow++;
}
fast++;
}
}
};
python版
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
fast=0
slow=0
for i in range(0,len(nums)):
if nums[i]!=0:
nums[fast],nums[slow] = nums[slow],nums[fast]
slow = slow+1
fast = fast+1
版权声明:本文为weixin_45042017原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。