Блог пользователя SAHAL01

Автор SAHAL01, история, 9 месяцев назад, По-английски

How to solve the problem below in O(log2n) C++: You have the i'th element of an unsorted array. you have to find the nearest(absolute difference of the values is as small as possible) element of the i'th element from the right side.

  • Проголосовать: нравится
  • -1
  • Проголосовать: не нравится

»
9 месяцев назад, # |
Rev. 3   Проголосовать: нравится +1 Проголосовать: не нравится

Impossible. You will spend at least O(n) to read everything and while you're reading you can just calc the answer.

if j > i: res = ...

If you're trying to solve for O(logn) per query. You can do binary search on set/sorted array etc.

  • »
    »
    9 месяцев назад, # ^ |
    Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

    I'm thinking about that too. but we can use set and lower_bound to complete the task.

»
9 месяцев назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

if you mean right side of the sorted array then you can use a set and do lower_bound on that to give the element just greater than your current element.

if you mean right side of the unsorted array then you can iterate from right and find the nearest element in the set i guess something like that although i admit this approach seems like it might not be that simple.

P.S. do tell the approach when you find it, it seems interesting :)

»
9 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

maintain a set, iterate from n to 1. for each i, find the value closest to a[i] on set (can be done using lower_bound), then insert a[i] into set