283. 移动零

题目:https://leetcode-cn.com/problems/move-zeroes/

我的想法:使用一个慢指针和一个快指针,慢指针则是用来寻找数组中“0”的位置,快指针用来遍历整个数组以找到不为“0”的元素,然后交互

代码:

C++版本:
void moveZeroes(vector<int>& nums) {
    int fastIndex = 0, slowIndex = 0;
    while ( fastIndex < nums.size()){
        if (nums[slowIndex] == 0 && nums[fastIndex] != 0){
            nums[slowIndex] = nums[fastIndex];
            nums[fastIndex] = 0;
            slowIndex++;
        }
        else if (nums[slowIndex] != 0){
                slowIndex++;
        }
        fastIndex++;
    }
}

JAVA版本:    
public void moveZeroes(int[] nums) {
    int fastIndex = 0, slowIndex = 0;
    while ( fastIndex < nums.length){
            if (nums[slowIndex] == 0 && nums[fastIndex] != 0){
                nums[slowIndex] = nums[fastIndex];
                nums[fastIndex] = 0;
                slowIndex++;
            }
            else if (nums[slowIndex] != 0){
                slowIndex++;
            }
            fastIndex++;
     }
 }

原文地址:https://www.cnblogs.com/wltree/p/15392183.html