題目:
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.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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.
思路:
此題是讓我們把數(shù)組中所有的0元素,移動到數(shù)組的結(jié)尾,要求我們不復(fù)制這個數(shù)組做改變,并且盡量減少操作次數(shù)。思考了一下,想到一個可以節(jié)省代碼量并且讓時間復(fù)雜度保持在O(n)的方案。
想法是這樣的:既然規(guī)定不復(fù)制這個數(shù)組,那就在它本身做文章了,我遍歷這個數(shù)組,如果出現(xiàn)不是零的數(shù),就讓它把原數(shù)組的第一位替換掉,這樣的話,這個數(shù)組就是去掉所有0的狀態(tài)了,在這之后,我們把這個數(shù)組結(jié)尾補0,一直補到原長度就好了。很簡單!
代碼:
public class Solution {
public void moveZeroes(int[] nums) {
int newArrayIndex = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[newArrayIndex++] = nums[i];
}
}
for (int i = newArrayIndex; i < nums.length; i++) {
nums[i] = 0;
}
}
}