1. Title Description
Given an array nums, write a function to move all zeros to the end of the array while preserving the relative order of the non-zero elements. Example:
Input:,1,0,3,12 [0]
Output:,3,12,0,0 [1]
Note: must operate on the original array, cannot copy additional arrays.
Minimize the number of operations.
Ii. Analysis of Ideas:
We can’t create new arrays. We can’t control subscripts.
Double subscript implementation is considered on the basis of time complexity.
Special attention needs to be paid to the control of subscripts for consecutive zeros.
Iii. AC Code:
class Solution {
public void moveZeroes(int[] nums) {
int index = 0;
for (int i = 0; i < nums.length-1; i++) {
if (nums[i] == 0){
nums[index] = nums[i+1];
index = nums[i+1] = =0 ? index : index+1;
nums[i+1] = 0;
}else{ index++; }}}}Copy the code
Iv. Summary:
One-dimensional array operations are mostly O(n).
“This article is participating in the” Gold Digging march Campaign “, click to see the details of the campaign.”