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:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

这个移动必须是在原地一动,不能借助其他的容器。

基本的思想是将所有的不是0的数都往前移动,最后在根据容器的最初大小补上0就可以了

 #include <vector>
using namespace std;
class Solution{
public:
void moveZeros(vector<int> & nums){
auto sz = nums.size();
int pos = ;
for (int i = ; i < sz; ++i){
if (nums[i] != )
nums[pos++] = nums[i];
}
for (int i = pos; i < sz; ++i)
nums[i] = ;
}
};

大体上就是这样

java版本代码如下:

public class Solution {
public void moveZeroes(int[] nums) {
int pos = 0;
for(int i = 0; i < nums.length; ++i){
if(nums[i] != 0){
nums[pos++] = nums[i];
}
}
while(pos < nums.length){
nums[pos++] = 0;
}
}
}

最新文章

  1. MySQL主从复制原理及配置详细过程以及主从复制集群自动化部署的实现
  2. Linux grep命令和正则表达式
  3. 清北学堂2017NOIP冬令营入学测试
  4. [daily][archlinux][pacman] local database 损坏
  5. 夺命雷公狗---node.js---2node.js中的npm的常用命令
  6. hdu 4604 Deque
  7. btr_cur_t;
  8. Java笔记(十四)&hellip;&hellip;抽象类与接口
  9. html-----003
  10. [CSS] Transforms
  11. JS高级程序设计学习笔记之数组
  12. UNIX网络编程卷1 server编程范式0 迭代server
  13. C#推送RTMP到SRS通过VLC进行取流播放!!
  14. ABP前端使用阿里云angular2 UI框架NG-ZORRO分享
  15. jQuery的属性,事件及操作
  16. ASP.NET Zero--单元测试
  17. 帝国cms打开慢
  18. Nginx+Tomcat+Https 服务器负载均衡配置
  19. C语言之指针变量
  20. python 开发环境配置

热门文章

  1. 【JUnit】junit4的几个assert方法
  2. [Python] Send emails to the recepients specified in Message[&quot;CC&quot;]
  3. [转]c# 画图中bitmap类处理出图片时,存储的注意事项
  4. Django:学习笔记(2)——创建第一个应用
  5. MAC brew软件安装
  6. 笔记-mysql 导出查询结果
  7. Spring中的定时调度(Scheduling)和线程池(Thread Pooling)
  8. $python数据分析基础——初识numpy库
  9. CentOS7种搭建FTP服务器
  10. FutureTask、Fork/Join、 BlockingQueue