Problem:

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

1. You must do this in-place without making a copy of the array.

2. Minimize the total number of operations.

Summary:

在不复制数组的情况下,将整型数组中的所有0移至数组末尾,其他数相对位置不变。

尽可能减少操作数。

Analysis:

1. 常规方法:用两个指针,其中一个指针向后扫,每找到一个非零元素则与前面指针内容互换。

 class Solution {
public:
void moveZeroes(vector<int>& nums) {
int len = nums.size(), k = ; for (int i = ; i < len; i++) {
if (nums[i] != ) {
swap(nums[i], nums[k++]);
}
} return;
}
};

但由于交换操作过多,导致效率不高。

2. 同样两个指针,其中一个指针向后扫,每找到一个非零元素则按顺序从数组头往后放,另一个指针记录当前放置位置。

  第一个指针扫完时,将第二个指针到数组末尾全部填0即可。

 class Solution {
public:
void moveZeroes(vector<int>& nums) {
int len = nums.size(), k = ; for (int i = ; i < len; i++) {
if (nums[i] != ) {
nums[k++] = nums[i];
}
} while (k < len) {
nums[k++] = ;
} return;
}
};

最新文章

  1. python爬虫学习(11) —— 也写个AC自动机
  2. java.lang.NoSuchMethodException: org.apache.ibatis.executor.statement.StatementHandler.prepare(java.sql.Connection)
  3. spring--基本介绍
  4. window 下Qt for android 环境搭建
  5. Yii 验证码验证
  6. Node v4.1.1
  7. codevs2822 爱在心中
  8. UIGraphicsBeginImageContext - 位图上下文
  9. Android中Sqlite数据库进行增删改查
  10. C语言课设——电影院选票系统
  11. 用批处理修改hotst文件提示“拒绝访问”解决方法
  12. 浅谈MFC类CrackMe中消息处理函数查找方法
  13. mybatis-高级结果映射之一对一
  14. ANT入门&amp;用ANT编译java项目
  15. slice()
  16. 链接克隆、完整克隆 vmware 快照和克隆
  17. JS 运行、复制、另存为 代码。
  18. Python-Web框架的本质
  19. echarts 分组绘制柱状图
  20. jQuery阻止向上冒泡事件

热门文章

  1. linq学习
  2. [译]了解AngularJS $resource
  3. HDOJ 1520 Anniversary party
  4. POJ 2411 Mondriaan&amp;#39;s Dream
  5. 【PHP面向对象(OOP)编程入门教程】2.什么是类,什么是对象,类和对象这间的关系
  6. unslider.js源码
  7. 简单实现div遮罩
  8. CSS继承总结
  9. Android学习笔记(十三)——广播机制
  10. 剑指Offer 链表中倒数第k个结点