这篇文章给大家分享的是有关LeetCode如何移动零的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
1,问题简述
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
2,示例
示例:输入: [0,1,0,3,12]输出: [1,3,12,0,0]说明:必须在原数组上操作,不能拷贝额外的数组。尽量减少操作次数。
3,题解思路
双指针的使用
4,题解程序
public class MoveZeroesTest {public static void main(String[] args) {int [] nums={0,1,0,3,12};moveZeroes(nums);for (int num:nums) {System.out.print(num+"/t");}}public static void moveZeroes(int[] nums) {if (nums == null || nums.length == 0) {return;}int length = nums.length;int index = 0;for (int i = 0; i < length; i++) {if (nums[i] != 0) {nums[index++] = nums[i];}}while (index < length) {nums[index++] = 0;}}}
5,题解程序图片版

感谢各位的阅读!关于“LeetCode如何移动零”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
原创文章,作者:bd101bd101,如若转载,请注明出处:https://blog.ytso.com/tech/opensource/223617.html