Skip to content

Instantly share code, notes, and snippets.

@ozkansari
Created April 12, 2020 18:22
Show Gist options
  • Save ozkansari/ac4265bf3c4e19c843b9482a9ffe11f0 to your computer and use it in GitHub Desktop.
Save ozkansari/ac4265bf3c4e19c843b9482a9ffe11f0 to your computer and use it in GitHub Desktop.
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3286/
import java.util.Arrays;
import java.util.stream.Collectors;
public class MoveZeroes {
public static void main(String[] args) {
MoveZeroes problem = new MoveZeroes();
int[] result1 = problem.calculate(new int[] { 0, 1, 0, 3, 12 });
System.out.println(
"Expected: [1,3,12,0,0], " + "Result: " + Arrays.stream(result1).boxed().collect(Collectors.toList()));
}
/**
* Given an array nums, write a function to move all 0's to the end of it while
* maintaining the relative order of the non-zero elements.
*
* @param nums
* @return
*/
public int[] calculate(final int[] nums) {
int[] result = Arrays.copyOf(nums, nums.length);
int countZero = 0;
boolean moveNums = false;
for (int i = 0; i < result.length; i++) {
if (result[i] == 0) {
countZero++;
moveNums = true;
} else if (moveNums) {
result[i - countZero] = result[i];
}
}
while (countZero > 0) {
result[result.length - countZero] = 0;
countZero--;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment