题目链接
leetcode
题目描述
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
C++ 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #include <iostream> #include <vector> using namespace std;
class Solution { public: void moveZeroes(vector<int>& nums) { int right = 0; for (const int& num : nums) { if (num != 0) { nums[right++] = num; } } for (int i = right; i < nums.size(); i++) { nums[i] = 0; } } };
class Solution_1 { public: void moveZeroes(vector<int>& nums) { int n = nums.size(); int left = 0, right = 0;
while (right < n) { if (nums[right] != 0) { swap(nums[left], nums[right]); left++; } right++; } } };
void printArray(const vector<int>& nums) { cout << "["; for (size_t i = 0; i < nums.size(); i++) { cout << nums[i]; if (i != nums.size() - 1) cout << ","; } cout << "]" << endl; }
int main() { Solution solution; vector<vector<int>> nums_cases = { {0,1,0,3,12}, {0} }; for (auto& nums : nums_cases) { cout << "Input: "; printArray(nums);
solution.moveZeroes(nums); cout << "Output: "; printArray(nums); } return 0; }
|