1. 程式人生 > >LeetCode刷題Easy篇Move Zeroes

LeetCode刷題Easy篇Move Zeroes

題目

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.

十分鐘嘗試

沒有思路,看了牛人的答案,發現很牛逼。

1 遍歷陣列,如果num不等於0,nums[i]=num.如果等於0,後面不等於0的元素填充。目的是讓不等於0的元素移動到前面。

2. 如果最後填充後,後面有剩餘空間,全部填充為0,根本不用比較和移動。

class Solution {
    public void moveZeroes(int[] nums) {
        int index=0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=0){
                nums[index++]=nums[i];
            }
        }
        while(index<nums.length){
            nums[index++]=0;
        }
        
    }
}