Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

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

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

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
  • Проголосовать: не нравится

»
13 месяцев назад, # |
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.

»
13 месяцев назад, # |
  Проголосовать: нравится 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