题目:
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.
就是将一个数组中的所有为零的数后移,放到数组的最后,而其他元素前移,但是得保证元素的相对位置不变。这道题一开始我没有想到好的方法,只能机械地来移动,也就是首先外层一个循环来进行判断是否这个元素为零,如果为零,那么就将此元素直接放到数组的最后一个,并且从这个位置开始,将之后的所有元素前移,最后得考虑一个问题,那就是移动后的数据的那个i要减1,因为要保持从那个位置往后再进行循环来查找元素是否为零。
public class Solution
{
public static void moveZeroes(int[] nums)
{
int length = nums.length;
int i,j,numzero = 0;
for(i = 0; i < length; i++)
{
if(nums[i] == 0)
{
numzero += 1;
for(j = i; j < length - 1; j++)
{
nums[j] = nums[j+1];
}
nums[length - 1] = 0;
//i = 0;
i = i - 1; //这里要注意当一次判断为零出现时候,这个i在之前的循环中已经加了1,但是之后的循环我需要减1,从原来的位置重新开始,因为原来那个位置的数已经移动到最后一个位置了
}
if(numzero + i == length)
break;
}
//for(int z = 0; z < length; z++)
//System.out.print(nums[z] + " ");
}
}
本文讨论了如何在不复制数组的情况下,通过在数组中移动零元素,将其全部移动到数组末尾,同时保持非零元素的相对顺序不变。提供了一个具体的实现方法和示例,帮助理解算法细节。
420

被折叠的 条评论
为什么被折叠?



