What is the best data structure for storing 2-tuples (a, b) that support adding, removing tuples and comparing (on a or b))

So here is my problem. I want to save a 2-tuple (key, val) and want to perform the following operations:

  • are strings and values ​​are integers
  • multiple keys may have the same value
  • adding new tuples
  • update of any key with a new value (any new value or updated value is larger than the previous one, for example, timestamps)
  • selection of all keys with values ​​less than or greater than the specified value
  • removal of tuples.

Hash seems to be the obvious choice for updating a key's value, but then searching for the values ​​will take longer (O (n)). Another option is a balanced binary search tree with key and value switching. So, now searching by values ​​will be fast (O (lg (n))), but updating the key will take (O (n)). So, is there any data structure that can be used to solve these problems?

Thank.

+3
source share
4 answers

2 , - , , . , , . - + . , - O (log n). , , . O (log n + k).

- . , .

+2

O (logN) O (n) . . , .

0

.

  • ( O (log n)).
  • Hash based ( - O (1), - O (n)).

.

, ( ), ( , RDBMS ). , , .

0

, .

those. hash table from keys->valuesand another hash table from values->lists of keys.

class Foo:
    def __init__(self):
        self.keys = {} # (KEY=key,VALUE=value)
        self.values = {} # (KEY=value,VALUE=list of keys)

    def add_tuple(self,kd,vd):
        self.keys[kd] = vd
        if self.values.has_key(vd):
           self.values[vd].append(kd)
        else:
            self.values[vd] = [kd]

f = Foo()
f.add_tuple('a',1)
f.add_tuple('b',2)
f.add_tuple('c',3)
f.add_tuple('d',3)

print f.keys
print f.values

print f.keys['a']
print f.values[3]

print [f.values[v] for v in f.values.keys() if v > 1]

CONCLUSION:

{'a': 1, 'c': 3, 'b': 2, 'd': 3}

{1: ['a'], 2: ['b'], 3: ['c', 'd']}

1

['c', 'd']

[['b'], ['c', 'd']]
0
source

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


All Articles