Create 283. Move Zeroes.md

This commit is contained in:
唐树森 2018-09-07 11:05:13 +08:00 committed by GitHub
parent 82d57d85b5
commit 60bcb36cd6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

20
283. Move Zeroes.md Normal file
View File

@ -0,0 +1,20 @@
# [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++
```
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;
}
};
```