Algorithm for saving elements in the order of maintaining the array

I have one random number generator that generates a number between 1 to k. I also have an array of type int(ie int[]), whose size N, where kless than N.

Now the problem is that I need to save the unique generated numbers into an array (the deviation of the generated duplicate number) and maintain the order of the generated numbers without using additional space and complexity O(N). ie in the same array I also need to maintain the order of the generated number. So that I can get them in the generated order. No raster or additional arrays, etc. Not intended to be used.

This is not homework. This is one of the interview questions. I should not use the extra space. He asked me to use the fact that it is kless than N, and you need to implement the hashmap behavior in the same array. I suggested a lot of algorithms using extra spaces, but he also rejected the use of sorting, but I could not maintain the generated order.

+4
source share
1 answer

Well, I will not buy this homework. Here is the solution. Let k = 3, N = 5

Start:

ar[0] = 0
ar[1] = 0
ar[2] = 0
ar[3] = 0
ar[4] = 0

Create a random number. Suppose we need to store two bits of information:

  • "2" is the first random number.
  • "2".

So we do the following:

ar[0] = 2
ar[1] = 0
ar[2] = 10  // 10 is any number that larger than N.
ar[3] = 0
ar[4] = 0

next number: 4

ar[0] = 2
ar[1] = 4
ar[2] = 10  // taken
ar[3] = 0
ar[4] = 10  // taken

: 2

ar[2] >= 10 thus taken, try another number

: 1

ar[0] = 2
ar[1] = 14  // added 10 to signify it taken
ar[2] = 11  // added 1 as it the current number
ar[3] = 0
ar[4] = 10  // taken

.

, 10 , 10.

ar[0] = 2
ar[1] = 4
ar[2] = 1
ar[3] = 0
ar[4] = 0

- , [1..N]. [0..N-1], .

+5

All Articles