内网网站建设方案,wordpress 发帖验证码,石家庄网站建设兼职,网站建设需要懂的书籍移动零 题目 给定一个数组 nums#xff0c;编写一个函数将所有 0 移动到数组的末尾#xff0c;同时保持非零元素的相对顺序。 请注意 #xff0c;必须在不复制数组的情况下原地对数组进行操作。 答案1 class Solution {
public:void moveZeroes(vectorint nums…移动零 题目 给定一个数组 nums编写一个函数将所有 0 移动到数组的末尾同时保持非零元素的相对顺序。 请注意 必须在不复制数组的情况下原地对数组进行操作。 答案1 class Solution {
public:void moveZeroes(vectorint nums){
int nnums.size(),left0,right0;
while(rightn)
{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 (count0){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就自动的都排在后面了。