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元素后面第一个非0元素,并与其交换位置(复杂度太高!)
class Solution {
public void moveZeroes(int[] nums) {
// Arrays.sort(nums);
for(int i=0;i<nums.length;i++)
{
//寻找0
if(nums[i]==0)
{
//寻找该元素后面第一个非0元素,并与其交换
for(int j=i+1;j<nums.length;j++)
{
if(nums[j]!=0){
nums[i]=nums[j];
nums[j]=0;
break;
}
}
}
}
// System.out.println(Arrays.toString(nums));
}
}
方法2: 遍历数组,若当前的数不为0,依次放入nums,放完后,判断指针是否到达数组长度位置,没有的话就在后面插入0
class Solution {
public void moveZeroes(int[] nums) {
//方法2 遍历数组,若当前的数不为0,依次放入nums
//放完后,判断指针是否到达数组长度位置,没有的话就在后面插入0
int point=0;
for(int i=0;i<nums.length;i++)
{
if(nums[i]!=0){
nums[point++]=nums[i];
// point++;
}
}
while(point<nums.length){
nums[point++]=0;
}
}
}