我是靠谱客的博主 坚定小懒虫,这篇文章主要介绍283. 移动零 - 力扣,给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。,现在分享给大家,希望可以做个参考。
/**
- 解题思路:
- 先判断数组是否为空,或者其长度是否为0.
- 第二步,遍历出数组所有的元素,
- 第三步,如果某个元素不为0,则将其索引位置-index的值(第一位0)与其进行交换,常量+1
- 第四步,index往后的所有元素全部为0
*/
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public class Demo1 { 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];//赋值 index++; } } for (int i = index; i < nums.length; i++) { nums[i] = 0; } } public static void main(String[] args) { int nums[] = {0,0,0,10,1,0,0,0}; new Demo1().moveZeroes(nums); System.out.println(Arrays.toString(nums)); } }
最后
以上就是坚定小懒虫最近收集整理的关于283. 移动零 - 力扣,给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。的全部内容,更多相关283.内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复