283. Move Zeroes

问题:

将数组中的0移到末尾。

Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Example 2:
Input: nums = [0]
Output: [0]
 

Constraints:
1 <= nums.length <= 10^4
-2^31 <= nums[i] <= 2^31 - 1

  

解法:slow-fast pointers(快慢指针法)

  • 0~i-1:满足题意:非0元素数组
  • j:探测是否为非0元素
    • 若 j 是非0元素:交换 j 到第一个不满足【非0】的位置 i。
    • swap(i,j)
    • i++
  • 继续下一个元素的探测

代码参考:

 1 class Solution {
 2 public:
 3     void moveZeroes(vector<int>& nums) {
 4         int i=0, j=0;
 5         int n=nums.size();
 6         while(j<n){
 7             if(nums[j]!=0){
 8                 swap(nums[i], nums[j]);
 9                 i++;
10             }
11             j++;
12         }
13     }
14 };
原文地址:https://www.cnblogs.com/habibah-chang/p/14627608.html