[LeetCode]Design Twitter

题目描述:

LeetCode 355. Design Twitter design-twitter

Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods:

  1. postTweet(userId, tweetId): Compose a new tweet.
  2. getNewsFeed(userId): 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.
  3. follow(followerId, followeeId): Follower follows a followee.
  4. unfollow(followerId, followeeId): Follower unfollows a followee.

Example:

Twitter twitter = new Twitter();

// User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);

// User 1's news feed should return a list with 1 tweet id -> [5].
twitter.getNewsFeed(1);

// User 1 follows user 2.
twitter.follow(1, 2);

// User 2 posts a new tweet (id = 6).
twitter.postTweet(2, 6);

// User 1's news feed should return a list with 2 tweet ids -> [6, 5].
// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.getNewsFeed(1);

// User 1 unfollows user 2.
twitter.unfollow(1, 2);

// User 1's news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
twitter.getNewsFeed(1);

题目大意:

设计一个简化版的Twitter,用户可以发推文,关注/取消关注另一名用户,并且可以看到10条最新的推文推送。你的设计应当支持下列方法:

  1. postTweet(userId, tweetId): 发布一条新推文。
  2. getNewsFeed(userId): 获取最新的10条用户新闻推送。 每一条新闻都应当是该用户的关注对象或者用户自己发送的推文。 推文必须按照发布顺序倒序排列。
  3. follow(followerId, followeeId): 关注人关注一名用户。
  4. unfollow(followerId, followeeId): 关注人取消关注一名用户。

测试用例如题目描述。

解题思路:

Map + Set + PriorityQueue

系统应当维护下列信息:

1). 一个全局的推文计数器:postCount 用户发推文时,计数器+1

2). 推文Id -> 推文计数器的映射:tweetIdMap 用来记录推文的次序

3). 推文Id -> 用户Id的映射:tweetOwnerMap 用来记录推文的发送者是谁

4). 用户Id -> 关注对象集合的映射: followeeMap 用来记录用户的关注对象(关注/取消关注)

方法的实现:

1). 关注 follow / 取消关注 unfollow:

只需要维护followeeMap中对应的关注对象集合followeeSet即可

2). 发送推文 postTweet:

更新推文计数器postCount,维护tweetIdMap;

向用户的推文发送列表中新增一条记录

3). 获取推文推送 getNewsFeed:

这里需要使用优先队列PriorityQueue,记为pq

遍历用户的关注对象列表,将每一位关注对象的最新一条推文添加至pq中。

然后从pq中弹出最近的一条推文,记为topTweetId;

通过tweetOwnerMap找到这条推文的发送者userId,然后将该发送者的下一条比较新的推文添加至pq。

直到弹出10条最新的推文,或者pq为空为止。

Java代码:

public class Twitter {

    private int postCount;    
    private Map<Integer, Integer> tweetCountMap;
    private Map<Integer, List<Integer>> tweetIdMap;
    private Map<Integer, Integer> tweetOwnerMap;
    private Map<Integer, Set<Integer>> followeeMap;
    
    /** Initialize your data structure here. */
    public Twitter() {
        tweetCountMap = new HashMap<Integer, Integer>();
        tweetIdMap = new HashMap<Integer, List<Integer>>();
        tweetOwnerMap = new HashMap<Integer, Integer>();
        followeeMap = new HashMap<Integer, Set<Integer>>();
    }
    
    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
        tweetCountMap.put(tweetId, ++postCount);
        tweetOwnerMap.put(tweetId, userId);
        getTweetIdList(userId).add(tweetId);
    }
    
    /** 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) {
        List<Integer> result = new ArrayList<Integer>();
        Set<Integer> followeeSet = getFolloweeSet(userId);
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>(){
            @Override
            public int compare(Integer a, Integer b) {
                return tweetCountMap.get(b) - tweetCountMap.get(a);
            }
        });
        Map<Integer, Integer> idxMap = new HashMap<Integer, Integer>();
        for (Integer followeeId : followeeSet) {
            List<Integer> tweetIdList = getTweetIdList(followeeId);
            int idx = tweetIdList.size() - 1;
            if (idx >= 0) {
                idxMap.put(followeeId, idx - 1);
                pq.add(tweetIdList.get(idx));
            }
        }
        while (result.size() < 10 && !pq.isEmpty()) {
            Integer topTweetId = pq.poll();
            result.add(topTweetId);
            Integer ownerId = tweetOwnerMap.get(topTweetId);
            int idx = idxMap.get(ownerId);
            if (idx >= 0) {
                List<Integer> tweetIdList = getTweetIdList(ownerId);
                pq.add(tweetIdList.get(idx));
                idxMap.put(ownerId, idx - 1);
            }
        }
        return result;
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    public void follow(int followerId, int followeeId) {
        getFolloweeSet(followerId).add(followeeId);
    }
    
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    public void unfollow(int followerId, int followeeId) {
        if (followerId != followeeId) {
        	getFolloweeSet(followerId).remove(followeeId);
        }
    }

    /** Get a non-empty followee set of an user. */
    private Set<Integer> getFolloweeSet(int userId) {
        Set<Integer> followeeSet = followeeMap.get(userId);
        if (followeeSet == null) {
            followeeSet = new HashSet<Integer>();
            followeeSet.add(userId);
            followeeMap.put(userId, followeeSet);
        }
        return followeeSet;
    }
    
    /** Get a non-empty tweet id list of an user. */
    private List<Integer> getTweetIdList(int userId) {
        List<Integer> tweetIdList = tweetIdMap.get(userId);
        if (tweetIdList == null) {
            tweetIdList = new ArrayList<Integer>();
            tweetIdMap.put(userId, tweetIdList);
        }
        return tweetIdList;
    }
    
}

/**
 * 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);
 */

Python代码可参考:https://leetcode.com/discuss/107656/python-solution

本文链接:http://bookshadow.com/weblog/2016/06/11/leetcode-design-twitter/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论