1. 程式人生 > >[LC]Move Zeroes

[LC]Move Zeroes

class num all div should code ++ col 一個

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.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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.

思路:

- 因為把‘0’這個常數丟到最後,所以我們就一個loop指針掃過去把不是這個常數的都直接改寫在前面的位置,然後再把剩下的位置改成這個特殊的常數。

- ‘in-place’改寫省空間。

- 找這個‘常數’特征可以寫一個特征filter(此處這個filter就是某常數)。

class Solution {
    public void moveZeroes(int[] nums) {
        int cur = 0;
        int len = nums.length;
        
for(int i = 0; i < len; i++){ if(nums[i]!=0){ nums[cur]=nums[i]; cur++; } } for(int i= cur; i<len; i++){ nums[i]=0;//index error: ‘i‘ vs. ‘cur‘ } } }

[LC]Move Zeroes