Given an array
nums
, write a function to move all0
'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.
解釋下題目:
把數(shù)組中的0全部移動到數(shù)組的最后,但是其他數(shù)字的相對位置不能變
1. 記錄下有多少個0就行了
實(shí)際耗時:0ms
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0 || nums.length == 1) {
return;
}
int cur = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int temp = nums[cur];
nums[cur++] = nums[i];
nums[i] = temp;
}
}
}
??首先需要明白一點(diǎn),我只需要盯著這些非零的數(shù)字,然后讓他們和0所在的位置進(jìn)行交換即可??梢钥吹酱a里每個非0的數(shù)字都會導(dǎo)致cur++,而cur就是目前nums[i]這個數(shù)字應(yīng)該在的位置。
時間復(fù)雜度O(n)
空間復(fù)雜度O(1)
拓展,如果我想讓所有的0都在前面呢?
只需要在循環(huán)的判斷語句中把不等于改成等于就行了。因?yàn)橹恍枰滥壳皀ums[i]前面有多少個0,就能知道它應(yīng)該放在哪里。