283. Move Zeroes - Easy

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:

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 pointer

fast pointer p1找非零元素,slow pointer p2用来赋值。当p1指向元素为0时, p1右移;当p1指向元素非0时,把当前元素赋给p2指向的元素,同时移动p1, p2。最后再把p2之后的元素全部赋0即可。

时间:O(N),空间:O(1)

class Solution {
    public void moveZeroes(int[] nums) {
        int p1 = 0, p2 = 0;
        while(p1 < nums.length) {
            if(nums[p1] != 0)
                nums[p2++] = nums[p1++];
            else
                p1++;
        }
        while(p2 < nums.length)
            nums[p2++] = 0;
    }
}

猜你喜欢

转载自www.cnblogs.com/fatttcat/p/10053595.html