Move Zeroes(Easy)

2019-08-19  本文已影响0人  海生2018

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:

You must do this in-place without making a copy of the array.
Minimize the total number of operations.


Solution:

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

Time:O(n)
Space:O(1)

不如C++ swap大法好,Java的交换应该也是一个操作吧,我觉得赋值可能更快,两个指针,idx负责不为零的数,i负责遍历数组

上一篇 下一篇

猜你喜欢

热点阅读