LeetCode/solutions/283. Move Zeroes.md

21 lines
826 B
Markdown
Raw Normal View History

2018-09-07 03:05:13 +00:00
# [283. Move Zeroes](https://leetcode.com/problems/move-zeroes/description/)
# 思路
题意就是将所有的0移到数组最后要求非0元素的相对顺序不变。
因为要求非0元素相对位置不变所以从后往前遍历遇到非0元素就前移合适的位置即可。
为了找到这个合适的位置用变量not_0记录当前元素之前有多少非0元素若当前元素也是非0元素则将该元素移到下标为not_0位置即可。
时间复杂度O(n)空间复杂度O(1)
# C++
2019-09-13 15:08:41 +00:00
```C++
2018-09-07 03:05:13 +00:00
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int not_0 = 0;
for(int i = 0; i < nums.size(); i++)
if(nums[i] != 0)
nums[not_0++] = nums[i];
for(int i = not_0; i < nums.size(); i++)
nums[i] = 0;
}
};
```