数据结构设计问题

air_snake 2010-09-18 02:17:33
[1] Design a layer in front of a system which cache the last n requests and
the responses to them from the system.
what data structure would you use to implement the cache in the later to
support following operations.
[a] When a request comes look it up in the cache and if it hits then return
the response from here and do not pass the request to the system
[b] If the request is not found in the cache then pass it on to the system
[c] Since cache can only store the last n requests, Insert the n+1th request
in the cache and delete one of the older requests from the cache

The objective is to achieve all the three operations in O(1).
...全文
175 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
zmr0469 2010-09-20
  • 打赏
  • 举报
回复
hash加忙链表,每次更新链表
绿色夹克衫 2010-09-20
  • 打赏
  • 举报
回复
循环队列+hash应该差不多,尤其是在实际应用当中,肯定可以,但如果细扣题目要求的话,可能还是稍微有些问题,但估计题目本意并不是非要一丝不差。
超级大笨狼 2010-09-19
  • 打赏
  • 举报
回复
这个用一个先入先出的栈来做。Stack<T>
air_snake 2010-09-19
  • 打赏
  • 举报
回复
不好意思,我看一个面试网站上的,懒得翻译,就没改。
我觉得用FIFO加hash应该可以了,被替换出去的,可以去hash里面找,然后删除
FIFO用链表,添加删除头尾也是O(1)的了。
xmx2009 2010-09-19
  • 打赏
  • 举报
回复
几个月没来,都变成了英语牛人了,佩服
yingkoz 2010-09-19
  • 打赏
  • 举报
回复
英文的!看不懂。
showjim 2010-09-19
  • 打赏
  • 举报
回复
hash指向单链表目标元素的上一结点,记录链表尾结点与当前结点数
zlntang 2010-09-19
  • 打赏
  • 举报
回复
下次能用中文不?
michaellufhl 2010-09-18
  • 打赏
  • 举报
回复

Usually, we could chose binary search tree to solve the problem. such as red-black tree.
michaellufhl 2010-09-18
  • 打赏
  • 举报
回复
So we may mix up 2 solutions: hash + linked list(queue as dingshaofengbinbin mentioned) which has 2 points to head and tail.

Each element is stored both in hash set and linked list(same reference).

a) Lookup:
hash set offers O(1).

b) Put and remove oldest element:
Add new : add the new one by head point in linked list, and put it in hash set.
Remove oldest: find the one by tail point in linked list, remove it both in hash set and list.

Sorry, the solution offers O(2) when put/remove.
air_snake 2010-09-18
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 dingshaofengbinbin 的回复:]

循环队列。。。
[/Quote]
这个不是查询不是O(1)吧
air_snake 2010-09-18
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 michaellufhl 的回复:]

Hash based data structure can offer O(1), and you need to fix the size of the hash structure.
[/Quote]
只用hash怎么替换oldest的。
dingshaofengbinbin 2010-09-18
  • 打赏
  • 举报
回复
循环队列。。。
michaellufhl 2010-09-18
  • 打赏
  • 举报
回复
Hash based data structure can offer O(1), and you need to fix the size of the hash structure.

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧