LeetCode——Move Zeroes
LeetCode——Move Zeroes
Question
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.
Solution
用两个指针,第一个指针找到第一个为0的位置i,然后另外一个指针从i+1开始找第一个不为0的位置j。然后交换两个数字即可,时间复杂度O(n)
Answer
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int i = 0;
int j;
while (1) {
int flag = 1;
int flag2 = 1;
while (i < nums.size()) {
if (nums[i] != 0)
i++;
else {
flag = 0;
break;
}
}
j = i + 1;
while (j < nums.size()) {
if (nums[j] == 0)
j++;
else {
flag2 = 0;
break;
}
}
if (flag == 1 || flag2 == 1)
break;
else {
int tmp;
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
for (int i = 0; i < nums.size(); i++)
cout << nums[i] << endl;
}
};
网上给出了一种更简单的写法
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j = 0;
// move all the nonzero elements advance
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[j++] = nums[i];
}
}
for (;j < nums.size(); j++) {
nums[j] = 0;
}
}
};