您的位置:首页 > 其它

Move Zeroes

2016-07-17 18:04 148 查看

Move Zeroes

作者:money

标签:leetcode,C++

问题:

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].

问题分析:

做了一个比较初级的解法。

用两个整数作为循环的指针。p0指向0元素,pn指向数字元素。p0发现0后,pn开始搜索非0数字,两个元素进行交换。循环至pn等于vector的长度。复杂度还是比较高,测试结果如下:

实现代码:

#include <iostream>
#include <vector>
// submit these code to leetcode
// begin
class Solution {
public:
void moveZeroes(std::vector<int>& nums) {
int p0,pn=0;
int psize=nums.size();
for(p0=0;pn<psize-1;p0++)
if(nums[p0]==0)
{
pn=p0;
while(nums[pn]==0&&pn<psize-1)
{
pn++;
}
printvec(nums,p0,pn);
std::swap(nums[p0],nums[pn]);
}
}

void printvec(std::vector<int> nums,int a,int b)
{
for(int i=0;i<nums.size();i++)
{std::cout<<nums[i]<<" ";}

std::cout<<std::endl<<"p0="<<a<<" pn="<<b<<std::endl;
}

};
// end
// submit these code to leetcode

int main(){
Solution s;
//test case
int ia[]={3,0,0,6,0,0,1,0,0,4,0,12};
std::vector<int> a(ia,ia+12);
//test case
s.moveZeroes(a);
for(int i=0;i < a.size();i++)
std::cout<<a[i]<<" ";

return 0;
}


杂录:

更快的方法,复杂度仅O(N)

直接一个个将非0数字按顺序放入序列前段,然后将vector剩下全置为0.

运行测试结果:



实现代码

#include <iostream>
#include <vector>
using namespace std;
// submit these code to leetcode
// begin
class Solution {
public:
void moveZeroes(std::vector<int>& nums) {
int j = 0;
// move all the nonzero elements advance
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[j++] = nums[i];
}
}
for (;j < nums.size(); j++) {
nums[j] = 0;
}
}
};
// end
// submit these code to leetcode

int main(){
Solution s;
//test case
int ia[]={3,0,0,6,0,0,1,0,0,4,0,12};
std::vector<int> a(ia,ia+12);
//test case
s.moveZeroes(a);
for(int i=0;i < a.size();i++)
std::cout<<a[i]<<" ";

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: