Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. # Q2:
  2. ## Design and implement a data structure for cache.
  3. * get(key) - Get the value of the key if the key exists in the cache, otherwise return -1; Average case of get(key) should be O(n) in computational complexity.
  4. * put(key, value, weight) - Set or insert the value, when the cache reaches its capacity, it should invalidate the least scored key. The scored is calculate as weight / ln(current_time - last_access_time)
  5.  
  6. Implement Step:
  7. 1. Creat a list to store the [key, value, weight], a dict to map the access time for the key.
  8. 2. get(key) ->
  9. * Key exits in the cache -> Reture the value of the key and update the access time for the key in the dict.
  10. * Key not exits in the cache -> return -1.
  11. 3. put(key, value, weight) ->
  12. * Check key if it is in the cache.
  13. * Remove the lowest score key in the list and dict if the key doesn't exist in the dictionary and the list is full capacity.
  14. * Add the new key to the list and dictionary.
  15.  
  16. Time complexity:
  17. 1. get(key) would spend O(len(list)) because of the dictionary implemented by list.
  18. 2. put(key) would spend O(capacity) to calculate the score.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement