LeetCode283. Move Zeroes(思维)
- Easy
- Accepted:407,019
- Submissions:763,123
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.
Example
Input: [0,1,0,3,12]
Output: [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.
链接
https://leetcode.com/problems/move-zeroes/
题意
给定一个数组,将其中所有为0的元素移到数组的末尾并保持非0元素的相对位置不变。
题解
- 直接暴力,统计一下0的个数再开一个辅助数组就行,时间复杂度$O(n)$,空间复杂度$O(n)$
- 对原数组进行遍历,先将所有的非0元素移到数组前面,最后再加上0元素,时间复杂度$O(n)$,空间复杂度$O(1)$
代码
- Runtime: 8 ms, faster than 100.00% of C++ online submissions for Move Zeroes.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
vector <int> ans;
int len = nums.size();
int cnt = 0;
for (int i = 0; i < len; ++i)
{
if (nums[i] != 0)
ans.push_back(nums[i]);
else
cnt++;
}
while (cnt--)
ans.push_back(0);
for (int i = 0;i < len; ++i)
nums[i] = ans[i];
}
};
- Runtime: 8 ms, faster than 100.00% of C++ online submissions for Move Zeroes.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int len = nums.size();
int cnt = 0;
for (int i = 0; i < len; ++i)
{
if (nums[i] != 0)
nums[cnt++] = nums[i];
}
for (int i = cnt; i < len; ++i)
nums[cnt++] = 0;
}
};
- 对原数组进行遍历,找到非0元素时,交换位置,最后无需再加上0元素
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int len = nums.size();
int cnt = 0; // [0, cnt)中均为非0元素
for (int i = 0; i < len; ++i)
{
if (nums[i] != 0)
swap(nums[cnt++], nums[i]);
}
}
};
The end.
2019年2月1日 星期五