LN : leetcode 283 Move Zeroes
2024-08-30 02:24:52
lc 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;
}
}
最新文章
- RCP:如何保存TaskList及如何获取TaskList
- Principle and Application of Database System
- bootstrap--input框选择日期
- erlang和java通信
- Unity3D判断鼠标向右或向左滑动,响应不同的事件
- Perl连接Sqlite数据库
- 阿里云主机和RDS使用心得
- php专业面试总结
- virtuoso数据库的安装方法
- Spring+SpringMVC+MyBatis的pom.xml依赖
- python语法_模块_time_datetime_random
- Macaca初体验-Android端(Python)
- docker仓库harbor搭建
- hive1.1.0安装
- day21 MRO和C3算法
- python3.3中print换行
- [PY3]——logging
- 最简单的socket通信
- MQTT的学习研究(五) MQTT moquette 的 Blocking API 发布消息服务端使用
- Linux中的阻塞机制