So I've heard a tricky question that Google apparently likes to ask during interviews:
You have been given an array of integers that may or may not contain zeroes. Your task is to sort the array in-place such that all the zeroes are at the last digits of the array, and all non-zero integers are at the beginning of the array in the order that they were initially given.
For instance,
sort([0, 0, 0]) //the new array is [0, 0, 0]
sort([1, 0, 1, 0, 0, 1, 1, 0, 1, 0]) //the new array is [1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
sort([0, 0, 7]) //the new array is [7, 0, 0], i.e. a much less interesting secret agent
sort([8, 6, 7]) //the new array is [8, 6, 7]
sort([5, 3, 0, 9]) //the new array is [5, 3, 9, 0], you got the wrong number
My code to solve it is at the bottom or on Pastebin as per usual.
I thought my method was interesting: I just left-shifted everything over whenever a zero was found, which means that the complexity was O(n^2) if I know my complexity theory (which I very well may not).
The most confusing part for me to code was the notallzeroes part of it. So I had to hard-code in the notallzeroes variable, which tracks the array to see if we can break: if we've reached the end of the non-zero part of the sorted array, we can break automatically. But it also allows us to see if there are any indices we need to go over again so we can redo those. The issue I ran into without that bit is that if multiple zeroes are in a row, every other zero is skipped.
import java.util.*;
public class Main {
static int[] array = new int[20];
public static void sort(int[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i] == 0) {
boolean notallzeroes = false;
for (int j = i; j < a.length - 1; j++ ){
a[j] = a[j+1];
if (a[j] != 0) {
notallzeroes = true;
}
}
a[a.length-1] = 0;
if (notallzeroes) {
i--;
}
else {
break;
}
}
}
}
public static void main(String[] args) {
System.out.println("STARTED!");
for (int j = 0; j < 20; j++) {
Random r = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = r.nextInt(100);
}
for (int i = 0; i < j; i++) {
array[r.nextInt(20)] = 0;
}
System.out.println("BEFORE: " + Arrays.toString(array));
sort(array);
System.out.println("AFTER: " + Arrays.toString(array));
}
}
}
No comments:
Post a Comment