題目:
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.
思路:
此題是讓我們把數組中所有的0元素,移動到數組的結尾,要求我們不復制這個數組做改變,并且盡量減少操作次數。思考了一下,想到一個可以節省代碼量并且讓時間復雜度保持在O(n)的方案。
想法是這樣的:既然規定不復制這個數組,那就在它本身做文章了,我遍歷這個數組,如果出現不是零的數,就讓它把原數組的第一位替換掉,這樣的話,這個數組就是去掉所有0的狀態了,在這之后,我們把這個數組結尾補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;
}
}
}