LeetCode: Move Zeroes
2017-04-15 13:58
141 查看
Given an array
to the end of it while maintaining the relative order of the non-zero elements.
For example, given
be
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;
}
}
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,
numsshould
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;
}
}
相关文章推荐
- LeetCode之Move Zeroes(Java+C)
- LeetCode题解:Move Zeroes
- leetcode283~Move Zeroes
- Leetcode-283 Move Zeroes
- Leetcode65: Move Zeroes
- leetcode-283-Move Zeroes
- LeetCode——Move Zeroes
- leetcode-283. Move Zeroes 在list里删除某个元素,并插入某个元素
- LeetCode——Move Zeroes
- LeetCode : Move Zeroes
- LeetCode:Move Zeroes
- [leetcode] Move Zeroes
- [Leetcode 283]Move Zeroes
- 【LeetCode】009 Move Zeroes 移零
- LeetCode-Move Zeroes
- [LeetCode]Move Zeroes
- LeetCode——Move Zeroes
- LeetCode 283 Move Zeroes
- leetcode: (283) Move Zeroes
- [leetcode]Move Zeroes