【LeetCode】283. Move Zeroes

Difficulty:easy

 More:【目录】LeetCode Java实现html

Description

https://leetcode.com/problems/move-zeroes/java

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.post

Example:ui

Input: 
Output: [0,1,0,3,12][1,3,12,0,0]

Note:this

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

Intuition

use two pointersspa

 

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)
code

Space complexity : O(1)htm

 

What I've learned

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

 

 More:【目录】LeetCode Java实现ip