Infinite Repeat Detection

What is the best way to find repetition in an infinite sequence of integers?

i.e. if in an infinite sequence the number "5" appears twice, then we will return the "false" first time and the "true" second time.

In the end, we need a function that returns "true" if the integer appeared earlier and "false" if the function received the integer for the first time.

If there are two solutions, one in space and one in time, then indicate both. I will write my decision in the answers, but I do not think this is the best option.

edit: Please do not accept trivial cases (i.e. repetitions, an ever-increasing sequence). I am interested in how to reduce the spatial complexity of a non-trivial case (random numbers with repetitions).

+1
source share
5 answers

I would use the following approach:

Use a hash table as your data structure. For each number you read, store it in your data structure. If it is already saved before you find a repetition.

If n is the number of elements in the sequence from the beginning to repetition, then this only requires O (n) time. The complexity of the time is optimal, since you need to at least read the elements of the input sequence to the point of repetition.

( )? ? . , , .

. , , , , ( ) .

: , , , . , . , , , .

+1

int (2 ^ 32 ) 512 . , BitSets , , mem .

BitSets, BitSets.

+1

, , . , , , , ( ). , , , (, , , ).

. , O (n), , , 1 . , : , List,

List changes // global

boolean addNumber(int number):
  boolean appeared = false
  it = changes.begin()
  while it.hasNext():
    if it.get() < number:
      appeared != appeared
      it = it.next()
    else if it.get() == number:
      if !appeared: return true
      if it.next().get() == number + 1
        it.next().remove() // Join 2 blocks 
      else 
        it.insertAfter(number + 1)  // Insert split and create 2 blocks
      it.remove()
        return false
    else: // it.get() > number
      if appeared: return true
      it.insertBefore(number)
      if it.get() == number + 1:
        it.remove() // Extend next block
      else:
        it.insertBefore(number + 1)  
  }
  return false
}

: . , , , , . ; [), , , , . appeared. , 5, 9, 6, 8, 7 ( ), :

[5,6)

[5,6), [9,10)

[5,7), [9,10)

[5,7), [8,10)

[5,10)

5 .

+1

TRUE

, .

, , , , , - .

0

, , , , O (N), N <= size (.. 2 ^ 32 # int) - , / .

, , -, , .

0

Source: https://habr.com/ru/post/1733311/


All Articles