Description:
https://leetcode.com/problems/move-zeroes/#/description
Algorithm:
- Use swap.
Code:
1 2 3 4 5 6 7 8 |
class Solution { public: void moveZeroes(vector& nums) { int numNonZero = 0; for (int i = 0; i < nums.size();i++) if (nums[i] != 0) swap(nums[numNonZero++], nums[i]); } }; |
Time & Space:
O(n) & O(1)