题目描述
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
参考代码
之前的辣鸡代码
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int length = nums.size();
if(length <= 1)
return;
for(int i = 0; i < length; i++){ // 注意两个指针的循环/遍历方向
if(nums[i] != 0)
continue;
for(int j = i; j < length; j++){
if(nums[j] != 0){
swap(nums[i], nums[j]);
break;
}
}
}
}
};
简单题,但是真正手写代码时还是得多举几个例子验证,注意代码的边界条件!
改进之后,用双指针,简单直白
题解参考:https://leetcode.cn/problems/move-zeroes/solutions/90229/dong-hua-yan-shi-283yi-dong-ling-by-wang_ni_ma/
类似快排的思路
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int length = nums.size();
if(length <= 1)
return;
int left = 0;
for (int right = 0; right < length; right++) {
if (nums[right] != 0) {
swap(nums[left++], nums[right]);
}
}
}
};
本文介绍了一种在原地操作的高效算法,用于将数组中所有零元素移动至数组末尾,同时保持非零元素的相对顺序不变。通过使用双指针技术,该算法能够显著减少不必要的元素交换,从而降低操作次数。
861

被折叠的 条评论
为什么被折叠?



