移动 0 的位置

移动 0 的位置 给定一个数组nums编写一个函数将所有0移动到数组的末尾同时保持非零元素的相对顺序。请注意必须在不复制数组的情况下原地对数组进行操作。示例 1:输入:nums [0,1,0,3,12]输出:[1,3,12,0,0]示例 2:输入:nums [0]输出:[0]提示:1 nums.length 104-231 nums[i] 231 - 1class Solution { public: void moveZeroes(vectorint nums) { int index0; for(int i0;inums.size();i){ if(nums[i]!0){ swap(nums[index],nums[i]); } } } };#include iostream #include vector #include algorithm // 包含swap函数 using namespace std; class Solution { public: void moveZeroes(vectorint nums) { // 双指针交换法 int nonZeroIndex 0; // 记录非零元素应放置的位置 for (int i 0; i nums.size(); i) { if (nums[i] ! 0) { swap(nums[nonZeroIndex], nums[i]); // 交换非零元素到前面 } } } }; // 打印数组 void printVector(const vectorint nums) { cout [; for (int i 0; i nums.size(); i) { cout nums[i]; if (i ! nums.size() - 1) { cout , ; } } cout ] endl; } int main() { // 测试用例1基础用例 vectorint nums1 {0, 1, 0, 3, 12}; cout 原数组1; printVector(nums1); Solution solution; solution.moveZeroes(nums1); cout 移动0后; printVector(nums1); return 0; }