1. 程式人生 > >283. Move Zeroes - Easy

283. Move Zeroes - Easy

his in-place 元素 move inter write solution function nta

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; } }

283. Move Zeroes - Easy