Move Zeros
来源:互联网 发布:中国名门望族排名,知乎 编辑:程序博客网 时间:2024/04/27 13:35
问题描述:
把数组的非0元素往前移动,0元素往后移动。要求do this in-place without making a copy of the array
解决:
因为空间复杂度的要求,不能创建一个数组来保存原数组中的非0元素。可以使用双指针来解决,与前面大部分的题类似做法。
/* * 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. */public class MoveZeros { public void moveZeroes(int[] nums) { if(nums == null || nums.length == 0) return; int index = 0; for(int i=0; i<nums.length; i++) { if(nums[i]!=0) { nums[index++] = nums[i]; } } for(int i=index; i<nums.length; i++) { nums[i] = 0; } }}一次遍历结束之后,做了把所有非0元素前移的工作。此外我们还需要把数组剩余的元素修改为0。
阅读全文
0 0
- move zeros
- Move Zeros
- Move Zeros
- 【leetcode】283. Move Zeros
- Leetcode Move Zeros
- (java)leetcode Move Zeros
- move zeros leetcode
- 【leetcode】:move zeros
- leetcode Move Zeros
- leetcode之move zeros
- Leetcode283 Move Zeros
- 283.move to zeros
- leetcode之 Move Zeros
- leetcode:Move Zeros
- 283.[LeetCode]Move Zeros
- LeetCode: Move Zeros
- leetCode:283.Move Zeros
- 283. Move Zeros
- 计算机网络-常识1
- Solr6.6.1 在 Tomcat7.0.56 部署,页面提示SolrCore Initialization Failures
- C/C++ 语言中函数参数传递的三种方式
- 【编程题】Java编程题二(10道)
- windows环境下C++实现的多种目录监控和优劣解析
- Move Zeros
- Two
- Kotlin中的const常量
- 都有哪些语言是跨平台的?
- C++拷贝构造函数详解
- VS2012编译boost1.53
- Android 函数绘画思路 Y=sinX 绘制过程;
- NotePad++快捷键总结
- 泛型注入