题目
283.MoveZeroes
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”移动到数组尾部,同时保持其余非零元素的相对位置不变。
例如,给定nums = [0, 1, 0, 3, 12],在调用你的函数之后,nums应该变为[1, 3, 12, 0, 0]。
备注:
你必须就地完成,不得复制该数组。
最小化总共的操作数。
(想看正解的跳过这段)这道题最初的想法是,先用循环将数组中为0的数的下标记录下来,然后在另一个循环中从被记录为0的地方开始,与下一个数依次两两交换,将第一个0移动到最后之后,再改动循环中数组的下标,改为第二个被记录为0的位置的下标。。。。。。。想象总是美好的,但是等写出来后暴露出一个很大的问题:随着一次次0被交换到最后,原先记录的数组中0的位置也随之改变,虽然每次只是前进一个位置,但是改完之后代码已经变得繁杂。
接下来换了种思路,只要保持相对位置不变就好了。当前的数字是0的话不做操作,非零的话将其与第一个零互换位置。
其核心在于这个第一个零的位置是如何变化的,即便一开始不是0也没关系,大不了让这个非零数和自己交换位置。
顺便贴上最优解的代码,思路和自解的差不多
package leetcode.array;
/**
* 283.MoveZeroes
* 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.
* @author 良
*/
//最优解
//class Solution {
// public void moveZeroes(int[] nums) {
// if(nums.length < 2) return;
// int k = 0;
// for(int i = 0; i < nums.length; i++) {
// if(nums[i] != 0) {
// nums[k++] = nums[i];
// }
// }
// for(;k < nums.length; k++)
// nums[k] = 0;
// for (int i=0;i<nums.length;i++ )
// System.out.print(nums[i]);
// }
//}
//自解
class Solution {
public void moveZeroes(int[] nums) {
int j;
for (int index = 0, current = 0; current < nums.length; current++) {
if (nums[current] != 0){
j=nums[index];
nums[index]=nums[current];
nums[current]=j;
index++;
}
}
for (int i=0;i<nums.length;i++ )
System.out.print(nums[i]);
}
}
public class MoveZeroes {
public static void main(String[] args){
Solution s=new Solution();
int[] num={1,0,0,3,7,1,2,1,};
s.moveZeroes(num);
}
}