设计题
1. LRU 缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
实现 LRUCache 类:
LRUCache(int capacity)以正整数作为容量capacity初始化 LRU 缓存int get(int key)如果关键字key存在于缓存中,则返回关键字的值,否则返回-1。void put(int key, int value)如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?
解题思路: 参考LinkedHashMap的实现方式。 HashMap + 双向链表。
public class LRUCache {
private HashMap<Integer, Entry> cache;
private Entry head;
private Entry tail;
private int capacity;
private int size;
public LRUCache(int capacity) {
cache = new HashMap<>();
this.capacity = capacity;
size = 0;
}
public int get(int key) {
if(!cache.containsKey(key)) {
return -1;
}
Entry e = cache.get(key);
afterAccess(e);
return e.value;
}
public void put(int key, int value) {
if(!cache.containsKey(key)) {
Entry e = new Entry(key,value);
cache.put(key,e);
afterInsertion(e);
size++;
} else {
Entry e = cache.get(key);
e.value = value;
cache.put(key, e);
afterAccess(e);
}
if(size > capacity) {
cache.remove(head.key);
removeHead();
}
}
private void removeHead() {
Entry e = head.next;
e.pre = null;
head = e;
size--;
}
private void afterAccess(Entry e) {
Entry before = e.pre;
Entry after = e.next;
if(before == null) {
Entry next = head.next;
if(next == null) {
return;
}
head = next;
next.pre = null;
tail.next = e;
e.pre = tail;
tail = e;
} else if( e == tail) {
return;
} else {
before.next = after;
after.pre = before;
tail.next = e;
e.pre = tail;
tail = e;
}
}
private void afterInsertion(Entry e) {
if(head == null) {
head = e;
} else {
tail.next = e;
e.pre = tail;
}
tail = e;
}
private static class Entry {
int key;
int value;
Entry pre;
Entry next;
public Entry(){}
public Entry(int key, int val) {
this.key = key;
this.value = val;
}
}
}
355. 设计推特 设计一个简化版的推特(Twitter),可以让用户实现发送推文,关注/取消关注其他用户,能够看见关注人(包括自己)的最近十条推文。你的设计需要支持以下的几个功能: postTweet(userId, tweetId): 创建一条新的推文 getNewsFeed(userId): 检索最近的十条推文。每个推文都必须是由此用户关注的人或者是用户自己发出的。推文必须按照时间顺序由最近的开始排序。 follow(followerId, followeeId): 关注一个用户 unfollow(followerId, followeeId): 取消关注一个用户 示例: Twitter twitter = new Twitter(); // 用户1发送了一条新推文 (用户id = 1, 推文id = 5). twitter.postTweet(1, 5); // 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文. twitter.getNewsFeed(1); // 用户1关注了用户2. twitter.follow(1, 2); // 用户2发送了一个新推文 (推文id = 6). twitter.postTweet(2, 6); // 用户1的获取推文应当返回一个列表,其中包含两个推文,id分别为 -> [6, 5]. // 推文id6应当在推文id5之前,因为它是在5之后发送的. twitter.getNewsFeed(1); // 用户1取消关注了用户2. twitter.unfollow(1, 2); // 用户1的获取推文应当返回一个列表,其中包含一个id为5的推文. // 因为用户1已经不再关注用户2. twitter.getNewsFeed(1); class Twitter { Map<Integer, List<Integer>> relationships; Map<Integer, List<int[]>> userBlogs; int count = 0; /** Initialize your data structure here. */ public Twitter() { userBlogs = new HashMap<>(); relationships = new HashMap<>(); } /** Compose a new tweet. */ public void postTweet(int userId, int tweetId) { if(userBlogs.containsKey(userId)) { userBlogs.get(userId).add(new int[]{tweetId, count++}); } else{ List<int[]> blogs = new ArrayList<>(); blogs.add(new int[]{tweetId, count++}); userBlogs.put(userId, blogs); } } /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ public List<Integer> getNewsFeed(int userId) { PriorityQueue<int[]> latestBolgs = new PriorityQueue<>((a, b) -> a[1] - b[1]); List<Integer> followees = relationships.get(userId); addToLatest(userId, latestBolgs); if(followees != null) { for(int followeeId : followees) { addToLatest(followeeId, latestBolgs); } } LinkedList<Integer> res = new LinkedList<>(); while(!latestBolgs.isEmpty()) { res.addFirst(latestBolgs.poll()[0]); } return res; } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ public void follow(int followerId, int followeeId) { if(relationships.containsKey(followerId)) { if(!relationships.get(followerId).contains(followeeId)) { relationships.get(followerId).add(followeeId); } } else{ List<Integer> followee = new ArrayList<>(); followee.add(followeeId); relationships.put(followerId, followee); } } /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ public void unfollow(int followerId, int followeeId) { if(relationships.containsKey(followerId)) { relationships.get(followerId).remove(Integer.valueOf(followeeId)); } } private void addToLatest(int userId, PriorityQueue<int[]> latestBolgs) { List<int[]> blogs = userBlogs.get(userId); if(blogs == null) return; for(int[] bid : blogs) { if(latestBolgs.size() < 10) { latestBolgs.offer(bid); continue; } if(latestBolgs.peek()[1] < bid[1]) { latestBolgs.poll(); latestBolgs.offer(bid); } } } } /** * Your Twitter object will be instantiated and called as such: * Twitter obj = new Twitter(); * obj.postTweet(userId,tweetId); * List<Integer> param_2 = obj.getNewsFeed(userId); * obj.follow(followerId,followeeId); * obj.unfollow(followerId,followeeId); */

浙公网安备 33010602011771号