Zero Mobile (Java)

Mobile Zero

topic:

Given the nums an array, a write function to all moved to the end of the array 0, while maintaining the relative order of nonzero elements.

thought:

Design a flag signal from scratch. Through the array to find a non-zero number will be placed at the index signal, signal ++, if the index is not equal to the current signal, the current index is pointing element assigned zero.

Code:

class Solution {
    public void moveZeroes(int[] nums) {
        int signal = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i]!=0){
                nums[signal] = nums[i];
            	if(i!=signal){
                	nums[i] = 0;
            	}
            	signal++;            
            }
    	}   
    }
}
Published 36 original articles · won praise 2 · Views 983

Guess you like

Origin blog.csdn.net/y18771025420/article/details/102575846