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.
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.
思路
(1)题目后半段读错了,以为题目的意思是把0移到后面,前面的元素按照升序排列:(,一定程度受到示例的影响。所以先让数组降序,然后再对前面非0部分做了首尾交换的升序排列。
(2)题目真正的意思:maintaining the relative order of the non-zero elements. 保持非零元素的相对位置不变。
(3)参见 遵守循环不变式(Java)——by liweiwei1419
解法1-错误
class Solution {
public void moveZeroes(int[] nums) {
int len = nums.length;
sort(nums, 0, len-1);
int i=0;
for(; i < len; i++){
if(nums[i]==0){
break;
}
}
i--;
int j = 0;
while(j < i){
int tmp = nums[i];
nums[i] =nums[j];
nums[j] = tmp;
i--;
j++;
}
}
private void sort(int[] arr, int left, int right){
if(left < right){
int mid = quickSort(arr, left, right);
sort(arr, left, mid-1);
sort(arr, mid+1, right);
}
}
private int quickSort(int[] arr, int left, int right){
int tmp = arr[left];
int i = left;
int j = right;
while(true){
while(i<=j && arr[i] >= tmp){
i++;
}
while(i<=j && arr[j] <= tmp){
j--;
}
if(i >= j){
break;
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
arr[left] = arr[j];
arr[j] = tmp;
return j;
}
}
解法2
(1)统计0的个数;
(2)有几个0,就把当前元素往前移动几个位置,相当于和0互换位置。
class Solution {
public void moveZeroes(int[] nums) {
int count = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0){
count++;
}else if(count > 0){
nums[i-count] = nums[i];
nums[i] = 0;
}
}
}
}