I am trying to finish a smoosh() method which will takes an array of ints. On completion the array should still contains the same numbers but wherever the array had two or more consecutive duplicate numbers, they are replaced by one copy of the number. Hence, after smoosh() is done, no two consecutive numbers in the array are the same.
Any unused elements at the end of the array are set to -1.
For example, if the input array is
[ 1 1 0 0 4 4 5 0 0 0 7 ]
it reads
[ 1 0 4 5 0 7 ]
after smoosh() completes.
The method signature is: public static void smoosh(int[] ints)
I was able to do it like this:
for (int i=0; i<ints.length-1; i++) {
if (ints[i+1]==ints[i])
ints[i]=-1;
}
for (int i=0; i<ints.length-1; i++) {
if (ints[i]==-1) {
for (int j=i+1; j<ints.length; j++) {
if (ints[j]!=-1) {
//swap ints[j] and ints[i] and then break;
}
}
}
}
However, this will be O(n2) time (although almost in place).
I feel like there should be some O(n) in place method to do this but I can't figure out how. Could anyone think of any O(n) in place algorithm? (Obviously if you make another array of the same size to help processing then you can get O(n) easily but that's not what I am looking for since that's not in place...)
thanks!