LeetCode(283): Move Zeros
Move Zeros: 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.
题意:移除给定数组中的0元素,将0元素移动到数组的末尾,并且保持不是0元素的元素的顺序。
思路: 可以利用一个指针将不是0 的元素尽可能的往前排,然后将剩余的全部设置为0。
代码:
public void moveZeroes(int[] nums) { int cnt =0,pos = 0; int len = nums.length; for(int i =0;i<len;i++){ //非0元素向前移 if(nums[i]!=0){ nums[pos] = nums[i]; pos++; } } //其余元素设置为0 for(;pos<len;pos++){ nums[pos]= 0; } }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步