Find the nth number that does not exist in the set

Given the set of missing numbers, I need to find the Nth number that does not exist in the set. Example:

Given the many [1, 4, 5], some results:

For N = 1, the result is 0

For N = 2, the result is 2 (because 1 is omitted)

For N = 3, the result is 3 (because 1 is omitted)

For N = 4, results 6 (because 1,4,5 are skipped)

This should work for a fairly large N, so a direct solution does not quite shorten it = (

+4
source share
1 answer

One way to do this is to create a helper array that tells you, for each index in the array, the number is lower than the values ​​below. For example, in this array:

1 4 5 9 13  (Array A)

this array will be

1 4 5 9 13  (Array A)
1 3 3 6 9   (Array B)

Array B O (n), :

  • B [0] = A [0] ( , ?)
  • B [n + 1] = B [n] + A [n + 1] - A [n] - 1. , . , n + 1, , n ( B [n]), , A [n + 1] A [n]. A [n + 1] - A [n] - 1..

: A [i] B [i] + i. ( ). ? , - B [i]. , , , B [i] + i.

, , " kth ?" O (log n), :

  • B ( , !), , k.
  • 0, k. , k- , k , . , , k.
  • (, x), x & ne; 0, , x - 1. B [x - 1] & le; k, , , , A [x - 1] A [x]. B [x] k, A [x - 1] A [x]. - A [x - 1] + k - B [x - 1] + 1.

, :

1 4 5 9 13  (Array A)
1 3 3 6 9   (Array B)

, . :

1 4 5 9 13  (Array A)
1 3 3 6 9   (Array B)
      ^

:

1 4 5 9 13  (Array A)
1 3 3 6 9   (Array B)
    ^

A [i] + k - B [i] + 1. 5 - 3 + 5 + 1 = 8. :

  • 0- 0
  • - 2
  • - 3
  • - 6
  • - 7
  • - 8.

: , 6-. :

1 4 5 9 13  (Array A)
1 3 3 6 9   (Array B)
        ^

:

1 4 5 9 13  (Array A)
1 3 3 6 9   (Array B)
      ^

, A [i] + k - B [i] + 1 = 9 + 6 - 6 + 1 = 10. .

, O (n), O (log n) .

, !

+5

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


All Articles