LeetCode/solutions/283. Move Zeroes.md
2019-09-13 23:08:41 +08:00

21 lines
826 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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++
```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;
}
};
```