c++ 33ms solution


  • 0
    J
     typedef struct MyTweets{
            int tweetId;
            int tweetTime;
        }MyTweets; 
    auto compare =[](const MyTweets& a, const MyTweets& b){return a.tweetTime>b.tweetTime;};
    class Twitter {
    
    
    	unordered_map<int, unordered_set<int>> followers;// <followeeId, followerId> the map to save the followers for each user
    	unordered_map<int, vector<MyTweets>> mp; //<userId, tweetIds> the map to save the users and their tweets
    	long long count;
    
    public:
    	/** Initialize your data structure here. */
    	Twitter() {
    		count = 0;
    	}
    
    	/** Compose a new tweet. */
    	void postTweet(int userId, int tweetId) {
    		MyTweets newTweets;
    		newTweets.tweetId = tweetId;
    		newTweets.tweetTime = count;
    		mp[userId].push_back(newTweets);
    
    		++count;
    	}
    
    	/** 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. */
    	vector<int> getNewsFeed(int userId) {
    		vector<MyTweets> newtweets;
    		//get up to 10 most recent tweets from user and each followers
    		int count = 0;
    		for (int i = mp[userId].size() - 1; i >= 0; i--)
    		{
    			if (count > 10)
    				break;
    			newtweets.push_back(mp[userId][i]);
    			++count;
    
    		}
    		
    		for (auto it = followers[userId].begin(); it != followers[userId].end(); ++it)
    		{
    			int count = 0;
    			for (int i = mp[*it].size() - 1; i >=  0; i--)
    			{
    				if (count > 10)
    					break;
    				newtweets.push_back(mp[*it][i]);
    				++count;
    			}
    		}
    
    		sort(newtweets.begin(), newtweets.end(), compare);
    		vector<int> res;
    		for (int i = 0; i<newtweets.size() && i<10; i++)
    			res.push_back(newtweets[i].tweetId);
    		return res;
    
    	}
    
    	/** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    	void follow(int followerId, int followeeId) {
            if(followerId != followeeId)
    		    followers[followerId].insert(followeeId);
    	}
    
    	/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    	void unfollow(int followerId, int followeeId) {
    	if(followers.find(followerId) != followers.end())
            followers[followerId].erase(followeeId);
    	}
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.