标签:
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
LeetCode:Move Zeroes - 将数组中的0移到最后
标签:
原文地址:http://my.oschina.net/Tsybius2014/blog/508653