注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
挂了 反正也没签NDA 报复性回报社会 把自己总结的面经po出来 这些题目mitbbs和本版上都讨论过 就那四道题 我只做了两道就挂了 就把这两道的解法贡献出来
Q: Implement set with integers in range {1…N}, implements five operations, add, remove, contains, clear, iterate. There are 3 versions to solve this 0, 1, 2
v1: using only bucket array with size N+1, the operation costs are: O(1),O(1), O(1), O(N), O(N) for example: if we add, 2, 0, 1, it will become list:[1, 1, 1]
v2: using only sequential array(store them sequentially in array): O(1),O(count),O(count),O(1), O(count)for example: if we add, 2, 0, 1, it will become map: [2, 0, 1] you need to keep an count
v3: achieve best of v1 and v2’s performance: O(1),O(1) O(1), O(1), O(count)
Note: I was thinking similar to LRU, using array + linkedlist. So that would make add, remove, contains and iterates optimal. But it doesn’t handle clear with O(1). 0, 1, 2 0, 1, 2
The right answer is to use the two array given. For bucket array value, it will be the index in the sequential array. The sequential array value will be the actually value. in the above example it will become list:[1, 2, 0], map[2, 0, 1]
A couple of things to notice: 1) how to remove? remove will not shift the rest of the array front, instead, it will pick the map[toRemove] = map[count - 1]; count—; 2) how to clear: map just need to set count to 0. 3) after cb.invoke();
}
}
// Now this looks good. We move on to fire(). Same as register, non-reentrant mutex can cause problem again with invoke(). So we should move invoke() outside.
void fire() {
m.acquire();
while(!q.isEmpty()) {
Callback cb = q.dequeue();
m.release();
cb.invoke();
m.acquire();
}
isFired = true;
m.release();
}
// Summary: exclude invoke() since we have no control; keep boolean isFired consistent with q status(q.isEmpty()), which is achieved by the last acquire and release.
|