Move Zeroes

来源:互联网 发布:轻松抠图软件 编辑:程序博客网 时间:2024/06/08 08:04
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.

给定一个数组nums,编写一个函数,在保持非零元素的相对顺序的同时,将所有的0移动到它的末尾。

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]


解题思路:本道题在最初求解时,没有理解题意,直接排序,然后将零移动到后面,但是是不可能通过的。

仔细考虑后,觉得可以使用快慢指针(严格说也不是):i指针从头开始,找到第一个零值,然后j在i的位置上,依次向后移,直到找到第一个非零值,之后交换即可。

详细代码如下:


public class Solution {    //应用快慢指针    int temp;    int j;    public void moveZeroes(int[] nums)    {            for(int i=0;i<nums.length-1;i++)            {              if(nums[i]==0)              {                j=i;                 while(nums[j]==0&&j<nums.length-1)                {                    j++;                }                temp=nums[i];                nums[i]=nums[j];                nums[j]=temp;                }                }         }}