您的位置:首页 > 其它

LeetCode: Move Zeroes

2017-04-15 13:58 141 查看
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都移动到数组的末尾,同时保持原来数组中其他非零元素的相对顺序,并且要求不能重新申请另外的数组空间,要求最小化要进行操作的元素数量。

解题思路:遍历数组,使用一个索引进行非零元素的插入操作,最后将剩下的全部元素全部赋值为0。时间复杂度为O(n),空间复杂度为O(1)

代码如下:
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) return;

int insertPos = 0;
for (int num: nums) {
if (num != 0) nums[insertPos++] = num;
}

while (insertPos < nums.length) {
nums[insertPos++] = 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: