LeetCode:Move Zeroes - 将数组中的0移到最后

一、题目名称java

Move Zeroes(将数组中的0移到最后)数组

二、题目地址函数

https://leetcode.com/problems/move-zeroescode

三、题目内容element

英文: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.leetcode

中文:给出一个数字数组,写一个函数将数组中全部的0移动到非0项的后面开发

例如:给出数组 nums  = [0, 1, 0, 3, 12] ,调用完函数后,数组元素的顺序会变为 [1, 3, 12, 0, 0]。get

注意:1)不能复制一个新数组;2)你须要最小化对数字的操做次数。it

四、解题方法io

完成本题须要下面两个步骤

1)将非0数字依次向前移动

2)将后面空出的部分所有补0

实现此方法的Java代码以下:

/**
 * 功能说明:LeetCode 283 - Move Zeros
 * 开发人员:Tsybius2014
 * 开发时间:2015年9月20日
 */
public class Solution {
    
    /**
     * 将数字0移动到最后
     * @param nums 输入数组
     */
    public void moveZeroes(int[] nums) {
        
        //将非0数字向前挪
        int cur = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[cur] = nums[i];
                cur++;
            }
        }

        //后面的元素所有补0
        for (int i = cur; i < nums.length; i++) {
            nums[i] = 0;
        }
    }
}

END

相关文章
相关标签/搜索