283. Move Zeroes
1. Description
Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
2. Example
Example 1:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
3. Note
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
4. Solutions
My Accepted Solution
n = m_nums.size()
Time complexity: O(n)
Space complexity: O(1)
class Solution
{
public:
// void moveZeroes(vector<int>& nums)
void moveZeroes(vector<int> &m_nums)
{
for(int i = 0, lastNonZeroIndex = 0; i++)
{
if(m_nums[i] != 0)
{
swap(m_nums[i], m_nums[lastNonZeroIndex]);
lastNonZeroIndex++;
}
}
}
};