LeetCode 283. Move Zeroes
原题链接在这里:https://leetcode.com/problems/move-zeroes/
题目:
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:
[0,1,0,3,12]
[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.
题解:
设置insertPo = 0, 每当遇到非零数,就赋值到nums[insertPo]上,同时insertPo++.
最后insertPo到nums.length位都填0.
Time Complexity: O(n). n = nums.length.
Space O(1).
AC Java:
1 public class Solution { 2 public void moveZeroes(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return; 5 } 6 7 int insertPo = 0; 8 for(int i = 0; i<nums.length; i++){ 9 if(nums[i] != 0){ 10 nums[insertPo++] = nums[i]; 11 } 12 } 13 14 while(insertPo < nums.length){ 15 nums[insertPo++] = 0; 16 } 17 } 18 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步