classTwitter { public: structtwitter{ int postTime; int tweetId; int userId; twitter *next; twitter(int x,int y,int z) : postTime(x), tweetId(y),userId(z), next(NULL){} }; int posttime=0; unordered_map<int,vector<int>>userfollow; unordered_map<int,twitter*>twitterlist; /** Initialize your data structure here. */ Twitter() {
}
/** Compose a new tweet. */ voidpostTweet(int userId, int tweetId){ twitter *newtwitter = new twitter(posttime,tweetId,userId); newtwitter->next = twitterlist[userId]; twitterlist[userId] = newtwitter; posttime++; }
/** 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<int>list; vector<int> ifollow = userfollow[userId]; ifollow.push_back(userId); int n = ifollow.size(),i=0; vector<twitter*>point(n); for(int i=0;i<n;i++)point[i]=twitterlist[ifollow[i]]; while(i<10){ int cnt=0; for(int i=0;i<n;i++){ if(point[i]==NULL)cnt++; } if(cnt==ifollow.size())break; int pt=-1,tid=0x3f3f3f3f,index=0; for(int i=0;i<n;i++){ if(!point[i])continue; if(pt < point[i]->postTime){ index=i; pt = point[i]->postTime; tid = point[i]->tweetId; } } if(pt!=-1){ point[index]=point[index]->next; list.push_back(tid); i++; } } returnlist; }
/** Follower follows a followee. If the operation is invalid, it should be a no-op. */ voidfollow(int followerId, int followeeId){ if(followerId == followeeId)return ; vector<int>t = userfollow[followerId]; bool flag=0; for(int i=t.size()-1;i>=0;i--){ if(t[i]==followeeId){ flag=1; break; } } if(flag)return ; userfollow[followerId].push_back(followeeId); }
/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ voidunfollow(int followerId, int followeeId){ if(followerId == followeeId)return ; vector<int>t = userfollow[followerId]; bool flag = 1; int n = t.size(),index=0; for(int i=0;i<n;i++){ if(t[i] == followeeId){ flag=0; index=i; break; } } if(flag)return; for(int i=index;i<n-1;i++){ t[i]=t[i+1]; } t.pop_back(); userfollow[followerId] = t; } };
/** * Your Twitter object will be instantiated and called as such: * Twitter* obj = new Twitter(); * obj->postTweet(userId,tweetId); * vector<int> param_2 = obj->getNewsFeed(userId); * obj->follow(followerId,followeeId); * obj->unfollow(followerId,followeeId); */