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