283.Move Zeroes
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:You must do this in-place without making a copy of the array.Minimize the total number of operations.
給定一個數組,需要把所有的0,移到數組的最后面,其他元素按照數組的前后順序排列。
要求:不能新建數組,而且最小化操作的次數。
我自己的錯誤解法
解法是遇到0的時候把這個元素移到最后面,然后其他元素往前移動1位,但是有個問題是,遇到[0,0,1]這種連續幾個0的數組時會報錯,因為移動之后,0往前移動,但是因為數組+1,所以并沒有判斷移到0位的數字。
public void moveZeroes (int nums []){
int length = nums.length;
int count = 0;
for (int i = 0; i <= length - 1; i++) {
if (nums[i] == 0 && (i + count < length)) {
count++;
for (int j = i; j <= length - 2 - i; j++) {
nums[j] = nums[j + 1];
}
nums[length - 1 - i] = 0;
}
}
正確解法
討論區的解法,是遍歷數組,然后初始化一個標記值為0,判斷數組中不為0元素的索引值,當數組不為0的時候,標記值自增,自增的次數代表 數組不包含為0的元素的索引值,其他不為0的元素只需賦值在這個索引值之后即可。
而在交換數組值的時候,只需要將為0數組的值賦給臨時變量,當前不為0的數組值賦給索引值為標記值的數組元素,然后將臨時變量賦給之前判斷的不為0的數組值。
例如: int [ ] nums = [ 1, 1, 0, 0, 0, 1 ] 判斷,cur++ 之后等于2,也即此時數組 nums[0]、nums[1]不為0,其他不為0的元素,只需賦給num[2]即可。而判斷語句就是實現這樣的功能:
temp = nums [2] , nums[2]=nums[5], nums[5]=temp
public void moveZeroes (int nums []) {
if (nums == null || nums.length == 0) {
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;
}
}
}