- 移动零
题目
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
答案1
class Solution {
public:void moveZeroes(vector<int>& nums){
int n=nums.size(),left=0,right=0;
while(right<n)
{if(nums[right]){swap(nums[left],nums[right]);left++;}right++;
}
}
};
答案2
class Solution {
public static void moveZeroes(int[] nums) {int count = 0;for (int i = 0; i < nums.length; i++) {if (nums[i] == 0) {count++;continue;}nums[i - count] = nums[i];}while (count>0){nums[nums.length-count]=0;count--;}}
}
这段代码实现了一个将数组中所有的0移到末尾的操作。具体解释如下:
初始化变量count为0,用于记录数组中0的个数。
使用for循环遍历数组nums。
如果当前元素为0,则将count加1,并使用continue语句跳过本次循环。
如果当前元素不为0,则将当前元素移动到新的数组位置nums[i - count]上。移动的过程中,利用count变量记录的0的数量,较大的i的值减去count,即为新的数组位置。
完成循环后,使用while循环遍历count次,将剩余的0放置在数组的末尾。通过nums.length-count计算得到新的0的位置,将其置为0,并将count减1。
通过上述操作,可以将数组中的所有0移动到末尾,并保持其他非零元素的相对顺序。
答案3
class Solution {
public: void moveZeroes(vector& nums)
{int pos = 0;for (int i = 0; i < nums.size(); i++){if (nums[i] != 0){swap(nums[i], nums[pos]);pos++;}}
}
};
可以采用逆向思维,他让去把零排后面,换个方法想就是把非零排前面,不打乱顺序。这样一趟循环就能判断完成。先保留一个pos作为没有交换过的位置,以便于后续出现非零元素可以保存,这样到最后结束的时候0就自动的都排在后面了。