<LeetCode OJ> Move Zeroes【283】
2015-12-23 09:45
537 查看
283. Move Zeroes
My SubmissionsQuestion
Total Accepted: 40008 Total
Submissions: 94323 Difficulty: Easy
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,
numsshould 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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
Array Two
Pointers
Show Similar Problems
朴素的模拟思想:O(N)
//想清楚思路:题目说了,必须原地处理,不能申请额外数组 //那么遍历数组一旦遇到0,就查找他后面第一个不是0的数,将其交换过来 class Solution { public: void moveZeroes(vector<int>& nums) { for(int i=0;i<nums.size();i++) { if(nums[i] == 0) { //找到第一个非0位置 int pos=i+1; while(pos<= nums.size()-1 && nums[pos]==0) pos++; //pos沿途都是0,包括最后一个元素 if(pos >= nums.size() -1 && nums[nums.size()-1]==0 ) break; //交换 nums[i]=nums[pos]; nums[pos]=0; } } } };
学习和参考一下别人家的解法1:(好简单直白的方式,速度稍微慢一点)
//将所有的非0数向前尽可能的压缩,最后把没压缩的那部分全置0就行了。比如103040,先压缩成134,剩余的3为全置为0 class Solution { public: void moveZeroes(vector<int>& nums) { int pos = 0; for (int i = 0; i < nums.size(); ++i){ if (nums[i] != 0) { nums[pos] = nums[i]; pos++; //利用pos记录压缩到的位置 } } //将后面的数全置为0 for (int j = pos; j < nums.size(); j++){ nums[j] = 0; } } };
学习和参考一下别人家的解法2:(给跪了)
可以参考快速排序的partition函数,根据是否为0来划分前后两部分。非0部分是从左往右扩展的可以发现相对顺序不变,0部分相对顺序虽然会变,但所有0都一样所以看不出差异的。
class Solution { public: void moveZeroes(vector<int>& nums) { int i=-1; for(int j=0;j<nums.size();++j) { if(nums[j]!=0) swap(nums[++i],nums[j]); } } };
参考资源:
【1】 网友,_bubble,原文地址,http://blog.csdn.net/rockzh1993/article/details/48971355
相关文章推荐
- 大幕拉开
- Python第三方库的安装方法
- Python游戏开发
- Oracle常用的OCI函数
- 【Linux】bool的使用
- JavaScript代码性能优化总结
- Objective-c语言_KVC
- Eclipse快捷键 10个最有用的快捷键
- LocationManager定位国内偏移,WGS-84、GCJ-02、BD-09之间转换
- 新AQI算法 之前算法错误
- Python ID3 DecisionTree
- Transfer Learning
- Yocto tips (10): Yocto hellworld 添加一个软件包
- 在Eclipse下debug 出现Source not found for ...
- Java垃圾收集器与内存分配策略
- 推荐几本javascript与jquery的好书
- python 面向对象
- 【转】Java 信号量 Semaphore 介绍
- 【Boost】boost库中timer定时器
- 2015年最受欢迎的8大用户界面开发工具