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

1、题目名称

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

2、题目地址

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

3、题目内容

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

中文:给出一个数字数组,写一个函数将数组中所有的0移动到非0项的后面

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

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

4、解题方法

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

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

转载于:https://my.oschina.net/Tsybius2014/blog/508653

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值