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:
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.
题解:
设置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 }