I came across an interview puzzle the other day where i was asked to write a program that removes duplicate entries in an integer array.
The pseudocode for solving this using a bit map data structure is below
a) for I : 1 to N do
bit[i] := 0;
b) for each integer I in input data do
bit[I] := 1;
c) for I: 1 to N do
if(bit[i] == 1) then
write to output int array.
import java.util.BitSet;
class RemoveDups {
public static void main(String[] args) {
// given input
int[] input = new int[] { 1, 4, 4, 2, 6, 18 };
// iterate through the array and set the bit to true for the corresponding integer
BitSet bset = new BitSet();
for (int i = 0; i < input.length; i++) {
bset.set(input[i]); // Sets the bit at the specified index to true
}
// iterate through the bset
int[] output = new int[input.length];
int count = 0;
for (int i = 0; i < bset.length(); i++) {
if (bset.get(i)) {
output[count++] = i;
}
}
}
}
Finally , the output array holds the list of distinct integers.
Saturday, April 24, 2010
Subscribe to:
Posts (Atom)