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.
Solutions:
(1) In the first loop, count the number of zeros.
In the second loop, if not zero, move forward; if zero, move backward.
(2) Note that the number behind #count zeros, need to move forward #count times.
C++
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int zerosNum = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] == 0) {
zerosNum++;
} else {
if (zerosNum != 0) {
int target = i - zerosNum;
nums[target] = nums[i];
nums[i] = 0;
}
}
}
}
};
(3) use index 'nonzero' to save the next to be saved nonzero place
C++
Two loops version:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int nonzero = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[nonzero++] = nums[i];
}
}
while (nonzero != nums.size()) {
nums[nonzero++] = 0;
}
}
};
Java:
// Shift non-zero values as far forward as possible
// Fill remaining space with zeros
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;
}
}
https://leetcode.com/problems/move-zeroes/discuss/72011/Simple-O(N)-Java-Solution-Using-Insert-Index
C++
One loop version:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int nonzero = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[nonzero] = nums[i];
if (i != nonzero)
nums[i] = 0;
nonzero += 1;
}
}
}
};
(4)
参考了快速排序的思想,快速排序首先要确定一个待分割的元素做中间点x,然后把所有小于等于x的元素放到x的左边,大于x的元素放到其右边。
这里我们可以用0当做这个中间点,把不等于0(注意题目没说不能有负数)的放到中间点的左边,等于0的放到其右边。
C++
class Solution {
public void moveZeroes(int[] nums) {
if(nums==null) {
return;
}
//两个指针i和j
int j = 0;
for(int i=0;i<nums.length;i++) {
//当前元素!=0,就把其交换到左边,等于0的交换到右边
if(nums[i]!=0) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j++] = tmp;
}
}
}
}
https://leetcode-cn.com/problems/move-zeroes/solution/dong-hua-yan-shi-283yi-dong-ling-by-wang_ni_ma/
void moveZeroes(vector<int>& nums) {
for (int lastNonZeroFoundAt = 0, cur = 0; cur < nums.size(); cur++) {
if (nums[cur] != 0) {
swap(nums[lastNonZeroFoundAt++], nums[cur]);
}
}
}
https://leetcode.com/problems/move-zeroes/solution/
Python
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
if not nums:
return 0
# 两个指针i和j
j = 0
for i in xrange(len(nums)):
# 当前元素!=0,就把其交换到左边,等于0的交换到右边
if nums[i]:
nums[j],nums[i] = nums[i],nums[j]
j += 1
https://leetcode-cn.com/problems/move-zeroes/solution/dong-hua-yan-shi-283yi-dong-ling-by-wang_ni_ma/