LeetCode-283:Move Zeroes (将数组中0元素移至尾部)
来源:互联网 发布:小学四年级体测数据 编辑:程序博客网 时间:2024/06/06 02:02
Question
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.
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元素移至数组末尾,非零元素顺序不变。注意在O(1)的空间复杂度内完成。
Answer
Solution 1:
加入位置指针,遍历赋值实现。
- 因为在题目中说明,非零元素顺序不变,所以这不构成一个排序问题;
- 加入一个数组位置指针,判断是否为0元素,不为0则赋值当前遍历的元素,位置指针自增1;否则跳过。
class Solution { public void moveZeroes(int[] nums) { if (nums == null || nums.length == 0) return; int index = 0; for (int num : nums){ if (num != 0){ nums[index++] = num; } } while (index < nums.length){ nums[index++] = 0; } return; }}
- 时间复杂度:O(n),空间复杂度:O(1)
阅读全文
0 0
- LeetCode-283:Move Zeroes (将数组中0元素移至尾部)
- (LeetCode)Move Zeroes -- 将元素0放到末尾
- Leetcode:283. Move Zeroes 把数组中为0的元素移到最后
- (数组)leetcode 283:Move Zeroes
- LeetCode 283. Move Zeroes (数组元素操作)
- 283. Move Zeroes (将数组中值为0的元素移到末尾)
- leetcode 283: Move Zeroes
- leetcode-283-Move Zeroes
- [leetcode 283]Move Zeroes
- LeetCode 283----Move Zeroes
- Leetcode #283 Move Zeroes
- leetcode: (283) Move Zeroes
- [LeetCode 283] Move Zeroes
- Leetcode 283 Move Zeroes
- leetcode 283--Move Zeroes
- LeetCode-----283Move Zeroes
- 【LEETCODE】283-Move Zeroes
- 【LeetCode】283Move Zeroes
- uiautomator中相同控件名该如何获取想要的控件,instance(0)区分布局一样的控件
- Hadoop中的文件格式
- 重复未名
- android studio 导入库文件
- Json串方括号开头手动解析数据简单案例
- LeetCode-283:Move Zeroes (将数组中0元素移至尾部)
- Python可视化学习笔记二
- python绘制动态模拟图
- xml html XHTML和json 区别
- python之文件读写
- 敏感词过滤
- Laravel应用目录结构
- 关于elasticsearch的先聚合和过滤、先过滤再聚合的详解
- 在百度云购买域名、阿里云购买服务器二者绑定过程