zoukankan      html  css  js  c++  java
  • 355. Design Twitter

    /**
    355. Design Twitter
    https://leetcode.com/problems/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.
    Implement the Twitter class:
    1. Twitter() Initializes your twitter object.
    2. void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId.
        Each call to this function will be made with a unique tweetId.
    3. List<Integer> getNewsFeed(int userId) Retrieves 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 themself.
        Tweets must be ordered from most recent to least recent.
    4. void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId.
    5. void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId.
    
    Example 1:
    Input
    ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
    [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
    Output
    [null, null, [5], null, null, [6, 5], null, [5]]
    Explanation
    Twitter twitter = new Twitter();
    twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
    twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]
    twitter.follow(1, 2);    // User 1 follows user 2.
    twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
    twitter.getNewsFeed(1);  // 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.unfollow(1, 2);  // User 1 unfollows user 2.
    twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.
    
    Constraints:
    1. 1 <= userId, followerId, followeeId <= 500
    2. 0 <= tweetId <= 10^4
    3. All the tweets have unique IDs.
    4. At most 3 * 10^4 calls will be made to postTweet, getNewsFeed, follow, and unfollow.
    */
    
    use std::collections::{
        HashMap,
        HashSet,
        LinkedList,
    };
    
    type user_id = i32;
    type tweet_id = i32;
    
    pub struct Twitter {
        tweets: LinkedList<(user_id, tweet_id)>,
        relations: HashMap<user_id, HashSet<user_id>>,
    }
    
    /**
     * `&self` means the method takes an immutable reference.
     * If you need a mutable reference, change it to `&mut self` instead.
     */
    
    impl Twitter {
        /*
       Solution: LinkedList to save tweets, HashMap to save relations
       */
        pub fn new() -> Self {
            Twitter {
                tweets: LinkedList::new(),
                relations: HashMap::new(),
            }
        }
    
        /**
        Composes a new tweet with ID tweetId by the user userId.
        Each call to this function will be made with a unique tweetId.
        */
        pub fn post_tweet(&mut self, user_id: i32, tweet_id: i32) {
            self.tweets.push_front((user_id, tweet_id));
        }
    
        /**
        Retrieves 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 themself.
        Tweets must be ordered from most recent to least recent.
        */
        pub fn get_news_feed(&mut self, user_id: i32) -> Vec<i32> {
            //take out tweets by user_id
            let mut result: Vec<i32> = self.tweets.iter().filter(|item| {
                if item.0 == user_id {
                    return true;
                }
                //take out tweets of user of user_id's following
                match self.relations.get(&user_id) {
                    Some(set) => return set.contains(&item.0),
                    None => return false,
                }
            }).take(10).map(|item| item.1).collect();
            result
        }
    
        /**
        The user with ID followerId started following the user with ID followeeId.
        */
        pub fn follow(&mut self, follower_id: i32, followee_id: i32) {
            self.relations.entry(follower_id).or_insert(HashSet::new()).insert(followee_id);
        }
    
        /**
        The user with ID followerId started unfollowing the user with ID followeeId.
        */
        fn unfollow(&mut self, follower_id: i32, followee_id: i32) {
            /*
            or_insert:
            Ensures a value is in the entry by inserting the default if empty,
            and returns a mutable reference to the value in the entry.
            */
            self.relations.entry(follower_id).or_insert(HashSet::new()).remove(&followee_id);
        }
    }
  • 相关阅读:
    IBM 2013策略发布:大数据和分析、云计算、企业移动、社交商务、智慧商务、智慧城市
    BakAndImgCD 6.0 发布,数据备份和映像
    YaCy 1.4 发布,分布式Web搜索引擎
    Pig安装及本地模式测试,体验
    GCC 4.7.3 发布
    UPUPW Nginx版PHP高配引擎发布
    如何选择基于云的大数据方案
    PortalBasic v3.1.1 beta1 示例工程发布
    LLVM 编译器架构获得 ACM 软件系统奖
    123 Flash Chat Server 9.9 发布
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/15685941.html
Copyright © 2011-2022 走看看