日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 355. 设计推特(哈希map+set)

發(fā)布時間:2024/7/5 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 355. 设计推特(哈希map+set) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1. 題目

設(shè)計(jì)一個簡化版的推特(Twitter),可以讓用戶實(shí)現(xiàn)發(fā)送推文,關(guān)注/取消關(guān)注其他用戶,能夠看見關(guān)注人(包括自己)的最近十條推文。你的設(shè)計(jì)需要支持以下的幾個功能:

  • postTweet(userId, tweetId): 創(chuàng)建一條新的推文
  • getNewsFeed(userId): 檢索最近的十條推文。每個推文都必須是由此用戶關(guān)注的人或者是用戶自己發(fā)出的。推文必須按照時間順序由最近的開始排序。
  • follow(followerId, followeeId): 關(guān)注一個用戶
  • unfollow(followerId, followeeId): 取消關(guān)注一個用戶
示例:Twitter twitter = new Twitter();// 用戶1發(fā)送了一條新推文 (用戶id = 1, 推文id = 5). twitter.postTweet(1, 5);// 用戶1的獲取推文應(yīng)當(dāng)返回一個列表,其中包含一個id為5的推文. twitter.getNewsFeed(1);// 用戶1關(guān)注了用戶2. twitter.follow(1, 2);// 用戶2發(fā)送了一個新推文 (推文id = 6). twitter.postTweet(2, 6);// 用戶1的獲取推文應(yīng)當(dāng)返回一個列表,其中包含兩個推文,id分別為 -> [6, 5]. // 推文id6應(yīng)當(dāng)在推文id5之前,因?yàn)樗窃?之后發(fā)送的. twitter.getNewsFeed(1);// 用戶1取消關(guān)注了用戶2. twitter.unfollow(1, 2);// 用戶1的獲取推文應(yīng)當(dāng)返回一個列表,其中包含一個id為5的推文. // 因?yàn)橛脩?已經(jīng)不再關(guān)注用戶2. twitter.getNewsFeed(1);

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/design-twitter
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。

2. 解題

struct cmp {bool operator()(const vector<int> &a, const vector<int> &b) const{return a[0] < b[0];} }; class Twitter {unordered_map<int,unordered_set<int>> m;//id,關(guān)注的人set<vector<int>,cmp> tweet;//time, 推文id,用戶idint time = 0;int count;vector<int> ans; public:/** Initialize your data structure here. */Twitter() {}/** Compose a new tweet. */void postTweet(int userId, int tweetId) {tweet.insert({time++, tweetId, 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. */vector<int> getNewsFeed(int userId) {count = 10;ans.clear();for(auto it = tweet.rbegin(); it != tweet.rend() && count; ++it){if((*it)[2]==userId || m[userId].count((*it)[2])){ans.push_back((*it)[1]);count--;}}return ans;}/** Follower follows a followee. If the operation is invalid, it should be a no-op. */void follow(int followerId, int followeeId) {m[followerId].insert(followeeId);}/** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */void unfollow(int followerId, int followeeId) {m[followerId].erase(followeeId);} };

532 ms 21.7 MB

總結(jié)

以上是生活随笔為你收集整理的LeetCode 355. 设计推特(哈希map+set)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。