美文网首页
Move Zeroes(Easy)

Move Zeroes(Easy)

作者: 海生2018 | 来源:发表于2019-08-19 18:55 被阅读0次

    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负责遍历数组

    相关文章

      网友评论

          本文标题:Move Zeroes(Easy)

          本文链接:https://www.haomeiwen.com/subject/zhiesctx.html