leetcode_Move Zeroes

来源:互联网 发布:视频放大的软件 编辑:程序博客网 时间:2024/06/17 22:33

描述:

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元素排列于数组的后面。大概思路就是用一个index标记最后一个非零元素的位置,遍历数组有一个非零元素则将index后移一位,直至遍历完所有元素,然后将从index开始到结束位置的所有元素置0

代码:

public class Solution {    public void moveZeroes(int[] nums) {        if(nums==null||nums.length<=1)            return;        int index=0;        for(int i=0;i<nums.length;i++)        {            if(nums[i]!=0)            {                nums[index++]=nums[i];            }        }        for(int i=index;i<nums.length;i++)        {            nums[i]=0;        }    }}


0 0
原创粉丝点击