Move all zeroes to end of array
来源:互联网 发布:估值建模 知乎 编辑:程序博客网 时间:2024/05/29 09:44
Move all zeroes to end of array
Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).
There can be many ways to solve this problem. Following is a simple and interesting way to solve this problem.
Traverse the given array ‘arr’ from left to right. While traversing, maintain count of non-zero elements in array. Let the count be ‘count’. For every non-zero element arr[i], put the element at ‘arr[count]‘ and increment ‘count’. After complete traversal, all non-zero elements have already been shifted to front end and ‘count’ is set as index of first 0. Now all we need to do is that run a loop which makes all elements zero from ‘count’ till end of the array.
public static void move(int[] arr) {if (arr == null || arr.length == 0) {return;}// index for non-zero int index = 0;for (int i = 0; i < arr.length; i++) {if (arr[i] == 0) {continue;} else {arr[index++] = arr[i];}}for (int i = index; i < arr.length; i++) {arr[i] = 0;}}public static void main(String[] args) {int[] arr = {0, 1, 2, 3, 0, 4, 5, 6, 7, 0};move(arr);for (int i = 0; i < arr.length; i++) {System.out.print(arr[i] + " ");}}
- Move all zeroes to end of array
- Move all zeroes to end of array
- 把零移动到数组的一端 Move all zeroes to end of array
- Given an array nums, write a function to move all 0's to the end of it while maintaining the relativ
- [Array]Move Zeroes
- LeetCode-Array-283. Move Zeroes
- [LC][Array]283. Move Zeroes
- vim separate with . and replace all to end of line
- leetcode283. [Array]Move Zeroes My Submissions Question
- 【leetcode】【Easy】【283. Move Zeroes】【array】
- Select n numbers from 1 to m with all of array 'all' and none of array 'none'
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- Move Zeroes
- 机器学习(Machine Learning)&深度学习(Deep Learning)资料
- 用求n!来比较while和for的不同
- IT 成长之路
- FMDB 简化 SQLite
- Android 异步加载网络图片并缓存到本地 软引用 学习分享
- Move all zeroes to end of array
- spring学习6-注解配置
- 【原创】《Linux高级程序设计》杨宗德著 - 进程管理与程序开发 - 等待信号
- 推荐!国外程序员整理的机器学习资源大全
- git进行版本控制
- C++学习建议
- 用循环队列实现打印杨辉三角(数据结构)
- java自学之路-----XML_解析技术
- 机器学习的最佳入门学习资源