efficiently find the first element matching a bit mask

后端 未结 4 506
小蘑菇
小蘑菇 2020-12-15 07:57

I have a list of N 64-bit integers whose bits represent small sets. Each integer has at most k bits set to 1. Given a bit mask, I would lik

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 08:36

    Construct a a binary tree as follows:

    1. Every level corresponds to a bit
    2. It corresponding bit is on go right, otherwise left

    This way insert every number in the database.

    Now, for searching: if the corresponding bit in the mask is 1, traverse both children. If it is 0, traverse only the left node. Essentially keep traversing the tree until you hit the leaf node (BTW, 0 is a hit for every mask!).

    This tree will have O(N) space requirements.

    Eg of tree for 1 (001), 2(010) and 5 (101)

             root
            /    \
           0      1
          / \     |
         0   1    0
         |   |    |
         1   0    1
        (1) (2)  (5)
    

提交回复
热议问题