Move Zeros solution in Java


  • 11
    K
    public void moveZeroes(int[] nums) {
    	int i = -1, j = 0;
    	while (j < nums.length) {
    		if (nums[j] != 0) {
    			swap(++i, j, nums);
    		}
    		j++;
    	}
    }
    
    public void swap(int i, int j, int[] nums) {
    	int temp = nums[i];
    	nums[i] = nums[j];
    	nums[j] = temp;
    }

  • 0
    S

    public static int processZeroInt(int[] nums) {

    	System.out.println("\n\tOriginal Array: " + Arrays.toString(nums));
    	int len = nums.length;
    	int temp;		
    	int totalZeros=0;
    	
    	for (int x=0;x<len;x++) {
    		if (nums[x] == 0) {
    			totalZeros+=1;
    		}
    	}
    	System.out.println("\tTotal Zeros: " + totalZeros);
    	
    	for (int i=0; i<len; i++) {
    		if (nums[i]==0) {
    			for (int j=i; j<len-1; j++) {
    				temp = nums[j+1];
    				nums[j+1] = nums[j];
    				nums[j] = temp;
    			}
    		}
    		System.out.println("\n\tProcessing: " + Arrays.toString(nums));
    	} // OUTER FOR-LOOP ENDs
    	
    	if (totalZeros == 0) {
    		System.out.println("\n\t No Zero present in the array.");
    		return 0;
    	}
    	
    	if (totalZeros !=0 && nums[len-totalZeros] == 0) {
    		System.out.println("\n\tProcessed Array: " + Arrays.toString(nums));
    		return 0;
    	}
    	return processZeroInt(nums);
    	
    } // processZeroInt() ENDs

  • 0
    S

    posting this in the leetcode compiler it says the method takes more time. Anyone has efficient way for this problem


  • 0
    A

    public void moveZeroes(int[] nums) {

        int counter = 0;
        List zeroIndexList = new ArrayList();
        for(int i=0; i<nums.length;i++) {
            if (nums[i]==0) {
             zeroIndexList.add(i);
            }
        }
        for(int i=0;i<zeroIndexList.size();i++) {
            for(int j = ((int)zeroIndexList.get(i) - counter); j < nums.length-1 ; j++) {
                nums[j] = nums[j+1];
            }
            nums[nums.length-1] = 0;
            counter++;
        }
    }

Log in to reply
 

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