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; }
相关文章推荐
- STL中的set容器的一点总结
- K-means算法原理实现
- 栈和队列面试题(一):栈和队列的相互实现
- evaluate-reverse-polish-notation
- js笔记5浏览器对象和history和screen
- 使用sphinx创建搜索引擎
- C++11新特性:range based for loop-范围for循环基本使用方法
- OWA简化登录设置OWA登录使用只输入用户名的方式
- SQLite经典语句大全
- Spark性能优化(2)——广播变量、本地缓存目录、RDD操作、数据倾斜
- 【2016CCCC团体程序设计天梯赛决赛】总集吐槽篇
- ulua(一)上手
- centos 6.5下cmake工具的安装与配置
- 9yin
- Android开发艺术探索1
- 关于学习的一些思考
- 部署exchange2010三合一:之十一:部署NLB
- Bug管理的一般流程
- Spark性能优化(1)——序列化、内存、并行度、数据存储格式、Shuffle
- struts2处理请求的过程分析