lc 283 Move Zeroes


283 Move Zeroes

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

analysation##

刚开始用了很蠢的方法,后来用STL很轻松就解决了!

solution1:蠢

void moveZeroes(vector<int> & nums) {
if (nums.size() <= 1) {
return;
} else {
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[sum] = nums[i];
sum++;
}
}
for (int i = sum; i < nums.size(); i++)
nums[i] = 0;
}
}

solution2:STL

int size = nums.size();
int pos = 0;
for (int i = 0; i < size; i++) {
if (nums[i] != 0) {
int temp = nums[i];
nums.erase(nums.begin() + i);
nums.insert(nums.begin() + pos, temp);
pos += 1;
}
}

最新文章

  1. RCP:如何保存TaskList及如何获取TaskList
  2. Principle and Application of Database System
  3. bootstrap--input框选择日期
  4. erlang和java通信
  5. Unity3D判断鼠标向右或向左滑动,响应不同的事件
  6. Perl连接Sqlite数据库
  7. 阿里云主机和RDS使用心得
  8. php专业面试总结
  9. virtuoso数据库的安装方法
  10. Spring+SpringMVC+MyBatis的pom.xml依赖
  11. python语法_模块_time_datetime_random
  12. Macaca初体验-Android端(Python)
  13. docker仓库harbor搭建
  14. hive1.1.0安装
  15. day21 MRO和C3算法
  16. python3.3中print换行
  17. [PY3]——logging
  18. 最简单的socket通信
  19. MQTT的学习研究(五) MQTT moquette 的 Blocking API 发布消息服务端使用
  20. Linux中的阻塞机制

热门文章

  1. Hadoop 知识
  2. Dell PowerEdgeServerT110II USB Boot更新
  3. JSP自己定义标签入门实例具体解释
  4. webpack—入门
  5. openstack (5)-- 部署 Neutron 网络服务
  6. [Canvas画图] 藏图阁(16) 人体穴位
  7. ios打地鼠游戏源代码
  8. nginxserver报403 forbidden错误的解决的方法
  9. Eclipse Import别人的源代码,出错解决过程
  10. Keil和IAR——使用笔记