Find duplicate in an array

后端 未结 5 1828
醉梦人生
醉梦人生 2021-01-14 16:45

Given a read only array of n + 1 integers between 1 and n, find one number that repeats in linear time using less than O(n) space and traversing the stream sequentially O(1)

5条回答
  •  耶瑟儿~
    2021-01-14 17:17

    I have a solution which requires O(sqrt(N)) space and O(N) time, and traverses the list twice -- assuming it is possible to calculate the integer square root in O(1) time (for arbitrary large N, this is likely at least an O(log(N)) operation).

    • First allocate an integer array A1 of size ceil(sqrt(N)), filled with 0.
    • Iterate through your array, for each element x
      • compute k=floor(sqrt(x))
      • increment A1[k]
      • If A1[k]>2k+1, there must be at least one duplicate between and (k+1)²-1. (For k=floor(sqrt(N)) the threshold is N-k²). Rememberk` and break first iteration
    • optionally delete first array
    • Allocate a boolean array A2 of size 2k+1 filled with false.
    • Iterate through all x again:
      • Check if A2[x-k²] is set, if yes, x is a duplicate
      • Otherwise, increment A2[x-k²]

    The solution should also work for larger and smaller arrays (does not need to be exactly N+1), and if there are no duplicates, the first iteration will run to the end. Both temporary arrays are O(k) (if you are pedantic, the first one is O(k*log(k)), since it must store integers up to size sqrt(N)).

提交回复
热议问题