mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 283. Move Zeroes.md
This commit is contained in:
parent
82d57d85b5
commit
60bcb36cd6
20
283. Move Zeroes.md
Normal file
20
283. Move Zeroes.md
Normal 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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user