程序退出循环,即使调试也无法理解为什么

Program exits loop, can't understand why even with debugging

它在示例 [0,0,1] 处失败,输出是 [0,1,0] 而不是 [1,0,0]。我在调试模式下查看了代码,当 p1 变为 0 时,它跳出了 for 循环,我不明白为什么,因为它应该再循环一次,然后递减到 -1 并退出循环.

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array.

Example 1:

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

Example 2:

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

package random.leetCode;

import java.util.Arrays;

public class MoveZeroes_TwoPointers_283 {
    public void moveZeroes(int[] nums) {
        int p2 = 0;
        int tempIndex = 0;
        int lastIndex = nums.length - 1;

        for (int p1 = nums.length - 1; p1>=0;  p1--)
        {
            if (nums[p1] == 0)
            {
                if (p1 == nums.length - 1 && nums.length == 1)
                {
                    break;
                }

                tempIndex = p1;
                p2 = p1 + 1;
                while (p2 <= lastIndex)
                {
                    int temp = nums[p1];
                    nums[p1] = nums[p2];
                    nums[p2] = temp;
                    p2 += 1;
                    p1 += 1;
                }
                p1 = tempIndex -1;
                lastIndex--;
            }
        }
    }

    public static void main(String[] args) {
        MoveZeroes_TwoPointers_283 example = new MoveZeroes_TwoPointers_283();
//       int[] numbersToBeSorted = new int[]{0,1,0,3,12,0,11,0,0};
//        int[] numbersToBeSorted = new int[]{0};
//        int[] numbersToBeSorted = new int[]{0,0};
//        int[] numbersToBeSorted = new int[]{1};
//        int[] numbersToBeSorted = new int[]{1,1};
       int[] numbersToBeSorted = new int[]{0,0,1};
        example.moveZeroes(numbersToBeSorted);
        System.out.println(Arrays.toString(numbersToBeSorted));
    }
}```
for (int p1 = nums.length - 1; p1>=0;  p1--) {
...
    tempIndex = p1;
...
    p1 = tempIndex -1;
}

您在此循环中将 p1 递减两次。你可能不是故意的。

有意思。我认为问题是当您找到两个连续的零并管理这些指针时。让我知道你对这个算法的看法。

void main() {
    int[] input = new int[]{0,0,1};
    
    // whenever finds a zero, move it to the end
    for (int i=0; i < input.length; i++) {
       if (input[i] == 0) moveToEnd(i, input);
    }

    System.out.println(input);
}

// move to the end by swapping elements
void moveToEnd(pos, arr) {
   for (int i = pos + 1; i < arr.length; i++) {
       int aux = arr[pos];
       arr[pos] = arr[i];
       arr[i] = aux;
       post = i;
   }
}