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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
// 1,0,0,3,12
// 1,3,0,0,12
// 1,3,12,0,0
public class Solution {
public void moveZeroes(int[] nums) {
if (nums == null || nums.length <= 1) {
return;
}
LinkedList<Integer> queue = new LinkedList<Integer>();
for (int i = 0; i < nums.length; i++) {
int n = nums[i];
if (n == 0) {
queue.add(i);
} else {
if (!queue.isEmpty()) {
int idx = queue.pop();
nums[idx] = n;
nums[i] = 0;
queue.add(i);
}
}
}
}
}
=====
public class Solution {
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
int firstZero = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
continue;
} else {
int tmp = nums[firstZero];
nums[firstZero] = nums[i];
nums[i] = tmp;
firstZero++;
}
}
}
}
========
public class Solution {
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
int start = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
if (i != start) {
nums[start] = nums[i];
}
start++;
}
}
while (start < nums.length) {
nums[start++] = 0;
}
}
}
没有评论:
发表评论