8.Move Zeroes(移动零)
Level:
Easy
题目描述:
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.
Example:
Input: [0,1,0,3,12]
Output: [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的元素,重新填充在原数组中,以index=0为下标开始,遇到一个不为0的元素,index加1。遍历完整个数组,然后从index开始,将index到数组尾部的所有元素都置为0,就得到了最终的结果。
代码:
class Solution {
public void moveZeroes(int[] nums) {
int index=0;
for(int i=0;i<nums.length;i++){
if(nums[i]!=0)
nums[index++]=nums[i];
}
for(int j=index;j<nums.length;j++){
nums[j]=0;
}
}
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步