【LeetCode】283. Move Zeroes

Difficulty:easy

 More:【目录】LeetCode Java实现

Description

https://leetcode.com/problems/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.

Intuition

use two pointers

 

Solution

    public void moveZeroes1(int[] nums) {
        int i=0, j=0;
        while(j<nums.length){
            if(nums[j]==0)
                j++;
            else
                nums[i++]=nums[j++];
        }
        while(i<nums.length)
            nums[i++]=0;
    }
    
    //better method
    public void moveZeroes(int[] nums) {
        int i=0;
        for(int n : nums){
            if(n!=0)
                nums[i++]=n;
        }
        while(i<nums.length)
            nums[i++]=0;
    }

  

Complexity

Time complexity : O(n)

Space complexity : O(1)

 

What I've learned

Thinking from 'nums[j] !=0' (the better method ) is better to understand than thinking from 'nums[j]==0'.

 

 More:【目录】LeetCode Java实现

 

posted @ 2019-10-09 10:53  华仔要长胖  阅读(268)  评论(0编辑  收藏  举报