283. Move Zeroes
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.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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.
题目大意:
给定一个数组,将所有的0移到数组后面并保持非0值顺序不变(不能占用额外的数组空间)
代码如下:
C++
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j = 0;
for(int i=0; i<nums.size(); i++)
{//将所有非零值移到前面
if(nums[i] != 0)
{
nums[j] = nums[i];
j += 1;
}
}
for(; j<nums.size(); j++)//剩下元素的全部赋值为0
nums[j] = 0;
}
void moveZeroes1(vector<int>& nums) {
int j = 0;
int num = nums.size();
for(int i=0; i<num; i++)
{
if(nums[i] != 0)
{
nums[j] = nums[i];//非零值 移位
if(i != j)
{//将移动的元素之前的位置赋值0
nums[i] = 0;
}
j += 1;
}
}
}
};
int main()
{
cout << "Hello world!" << endl;
return 0;
}
注意:
1.刚开始还以为还得把非零值排序,后来才发现非零值保持原来前后顺序不变就行了
2.第二种方法用一个循环就把完成了,移动元素的同时将之前位置赋值0