Java simple answer


  • 1
    S

    method1: exchange zero and non-zero

    public class Solution {
    public void moveZeroes(int[] nums) {
        for(int i = 0; i < nums.length-1; i++){
            if(nums[i] == 0 ){
                int j=i;
                while(nums[j] == 0 && j<nums.length-1){
                    j++;
                }
                nums[i] = nums[j];
                nums[j] = 0;
            }
        }
    }
    //algorithm : exchange value, the zero position exchange with the next non-zero position
    

    }

    method2: find non-zero put in new order, then all zero filled the array

    public class Solution {
    public void moveZeroes(int[] nums) {
        // change method, only find non-zero position and put those in order, then put all zero behind
        int order_pos = 0;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] != 0){
                nums[order_pos++] = nums[i];
            }
        }// i is used to find the non-zero postions
        
        while(order_pos < nums.length){
            nums[order_pos++] = 0;
        }
    }
    

    }


Log in to reply
 

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