//! 双指针 n,1 classSolution { public: voidmoveZeroes(vector<int> &nums){ int slow = 0; // slow point to non-zero,fast the other for (int fast = 0; fast < nums.size(); ++fast) { if (nums[fast] != 0) { swap(nums[slow], nums[fast]); ++slow; } } } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//!从后往前找0元素,找到就一步一步往后移 n^2,1 classSolution { public: voidmoveZeroes(vector<int> &nums){ int zeroTag, NonZeroTag; for (int i = nums.size() - 1; i >= 0; --i) { if (nums[i] == 0) { int j = i; while (j + 1 < nums.size() && nums[j + 1] != 0) { swap(nums[j], nums[j + 1]); ++j; } } } } };