Share my simple java solution (6 lines) inspired by "reverse words in a string"


  • 0
    T

    In "Reverse words in a string" this problem, we need to skip all the extra space when we process the final result. Here we can regard 0s as spaces, then my solution as follows:

    public void moveZeroes(int [] nums) {
    	int i = 0, j = 0;
    	int n = nums.length;
    	while (j < n) {
    		while (j < n && nums[j] == 0) j++;
    		while (j < n && nums[j] != 0) a[i++] = a[j++];
    	}
    	for (int k = i; k < n; k++) nums[k] = 0;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.