LeetCode OJ :Move Zeroes (移动0)
2024-09-25 13:12:49
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:
- You must do this in-place without making a copy of the array.
- 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;
}
}
}
最新文章
- MySQL主从复制原理及配置详细过程以及主从复制集群自动化部署的实现
- Linux grep命令和正则表达式
- 清北学堂2017NOIP冬令营入学测试
- [daily][archlinux][pacman] local database 损坏
- 夺命雷公狗---node.js---2node.js中的npm的常用命令
- hdu 4604 Deque
- btr_cur_t;
- Java笔记(十四)&hellip;&hellip;抽象类与接口
- html-----003
- [CSS] Transforms
- JS高级程序设计学习笔记之数组
- UNIX网络编程卷1 server编程范式0 迭代server
- C#推送RTMP到SRS通过VLC进行取流播放!!
- ABP前端使用阿里云angular2 UI框架NG-ZORRO分享
- jQuery的属性,事件及操作
- ASP.NET Zero--单元测试
- 帝国cms打开慢
- Nginx+Tomcat+Https 服务器负载均衡配置
- C语言之指针变量
- python 开发环境配置
热门文章
- 【JUnit】junit4的几个assert方法
- [Python] Send emails to the recepients specified in Message[";CC";]
- [转]c# 画图中bitmap类处理出图片时,存储的注意事项
- Django:学习笔记(2)——创建第一个应用
- MAC brew软件安装
- 笔记-mysql 导出查询结果
- Spring中的定时调度(Scheduling)和线程池(Thread Pooling)
- $python数据分析基础——初识numpy库
- CentOS7种搭建FTP服务器
- FutureTask、Fork/Join、 BlockingQueue