題目:
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元素顶捷,移動(dòng)到數(shù)組的結(jié)尾芝此,要求我們不復(fù)制這個(gè)數(shù)組做改變节值,并且盡量減少操作次數(shù)。思考了一下夭禽,想到一個(gè)可以節(jié)省代碼量并且讓時(shí)間復(fù)雜度保持在O(n)的方案。
想法是這樣的:既然規(guī)定不復(fù)制這個(gè)數(shù)組坛掠,那就在它本身做文章了咪奖,我遍歷這個(gè)數(shù)組盗忱,如果出現(xiàn)不是零的數(shù),就讓它把原數(shù)組的第一位替換掉羊赵,這樣的話趟佃,這個(gè)數(shù)組就是去掉所有0的狀態(tài)了,在這之后慷垮,我們把這個(gè)數(shù)組結(jié)尾補(bǔ)0揖闸,一直補(bǔ)到原長(zhǎng)度就好了。很簡(jiǎn)單料身!
代碼:
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;
}
}
}