LeetCode283. Move Zeroes

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.

Example:

1
2
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

Two Pointers

1

lc in cpp

1
2
3
4
void moveZeroes(vector<int>& nums) {
for (int left = 0, right = 0; right< nums.size();right++)
if (nums[right] != 0) swap(nums[right], nums[left++]);
}

题目要求O(1)space,那就用双指针,左边指向0,右边指向非零.当右边指到非零的时候,交换当前指向零的数即可.

Thanks for Support.