More:【目錄】LeetCode Java實現html
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
use two pointersspa
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; }
Time complexity : O(n)
code
Space complexity : O(1)htm
Thinking from 'nums[j] !=0' (the better method ) is better to understand than thinking from 'nums[j]==0'.blog
More:【目錄】LeetCode Java實現ip