Skip to content

Instantly share code, notes, and snippets.

@ozkansari
Created April 12, 2020 18:34
Show Gist options
  • Save ozkansari/0d757c4f101a101b1cf20065dff2af9b to your computer and use it in GitHub Desktop.
Save ozkansari/0d757c4f101a101b1cf20065dff2af9b 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 MoveZeroesOptimal {
public static void main(String[] args) {
MoveZeroesOptimal problem = new MoveZeroesOptimal();
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];
result[i] = 0;
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment