首页 > 其他分享 >[LeetCode] 1348. Tweet Counts Per Frequency 推文计数

[LeetCode] 1348. Tweet Counts Per Frequency 推文计数

时间:2023-06-14 14:25:44浏览次数:72  
标签:1348 推特 recordTweet Tweet Per getTweetCountsPerFrequency time tweet3 minute


A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minutehour, or day).

For example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies:

  • Every minute (60-second chunks): [10,69][70,129][130,189]...[9970,10000]
  • Every hour (3600-second chunks): [10,3609][3610,7209][7210,10000]
  • Every day (86400-second chunks): [10,10000]

Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example).

Design and implement an API to help the company with their analysis.

Implement the TweetCounts class:

  • TweetCounts() Initializes the TweetCounts object.
  • void recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds).
  • List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq.
    • freq is one of "minute""hour", or "day" representing a frequency of every minutehour, or day respectively.

Example:

Input
["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]
[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]

Output
[null,null,null,null,[2],[2,1],null,[4]]

Explanation
TweetCounts tweetCounts = new TweetCounts();
tweetCounts.recordTweet("tweet3", 0); // New tweet "tweet3" at time 0
tweetCounts.recordTweet("tweet3", 60); // New tweet "tweet3" at time 60
tweetCounts.recordTweet("tweet3", 10); // New tweet "tweet3" at time 10
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]; chunk [0,59] had 2 tweets
tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet
tweetCounts.recordTweet("tweet3", 120); // New tweet "tweet3" at time 120
tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]; chunk [0,210] had 4 tweets

Constraints:

  • 0 <= time, startTime, endTime <= 109
  • 0 <= endTime - startTime <= 104
  • There will be at most 104 calls in total to recordTweet and getTweetCountsPerFrequency.

这道题让统计特定时间段内推特的个数,有两个主要的函数需要实现,一个是 recordTweet,即记录下每次发某个推特的时间,这里的 tweetName 应该可以看作推特的话题,比如 HashTag 什么的,因为一般来说不会大量的发送完全相同的推特。另一个函数 getTweetCountsPerFrequency,让找出给定的起始和终止时间内,每分钟,或每小时,或每天发送某个话题的推特的个数。第一个函数比较容易实现,就是用一个数据结构记录下所有发送的推特,这里需要按照话题归类,因为最终也是按话题来找频率的,所以这里可以用一个 HashMap,来建立推特话题和所有该话题推特发出时间的集合之间的映射。这个集合到底是用 vector 呢,还是用可以自动排序的 HashSet 呢?

博主开始是纠结了一阵的,因为调用 recordTweet 时推特的时间可能是无序的,所以用 vector 的话得到的时间也就是无序的。要不要保留顺序取决于第二个函数该如何实现,给定了起始和结束时间,还有统计频率,分钟,小时或者天,那么就可以知道该时间段需要被分成多少个区间,就用结束时间减去起始时间,再除以频率,然后加1即可。关键是怎么统计每个区间内推特的个数,博主开始的想法是用二分查找,首先查找第一个不小于 startTime 的推特,然后再查找第一个不大于 startTime + freq 的推特,然后查找第一个不大于 startTime + 2*freq 的推特,以此类推,这种方法不但麻烦,而且容易出错。其实并不需要用二分查找,只需要遍历所有的推特,找出在大于等于起始时间,小于等于终止时间,然后计算其所在的区间序号,通过用当前时间减去起始时间,并除以频率即可,然后对应的区间里的次数加1即可,这种方法既简单又高效,参见代码如下:


class TweetCounts {
public:
    TweetCounts() {}
    
    void recordTweet(string tweetName, int time) {
        m[tweetName].push_back(time);
    }
    
    vector<int> getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) {      
        int n = (endTime - startTime) / freqMap[freq] + 1;
        vector<int> res(n);
        for (int time : m[tweetName]) {
            if (time >= startTime && time <= endTime) {
                int idx = (time - startTime) / freqMap[freq];
                ++res[idx];
            }          
        }
        return res;
    }

private:
    unordered_map<string, vector<int>> m;
    unordered_map<string, int> freqMap{{"minute", 60}, {"hour", 3600}, {"day", 86400}};
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1348


类似题目:

Design Video Sharing Platform


参考资料:

https://leetcode.com/problems/tweet-counts-per-frequency/

https://leetcode.com/problems/tweet-counts-per-frequency/solutions/504456/c-accepted-solution-with-map/

https://leetcode.com/problems/tweet-counts-per-frequency/solutions/503453/java-treemap-accepted-solution-easy-understand/


LeetCode All in One 题目讲解汇总(持续更新中...)

标签:1348,推特,recordTweet,Tweet,Per,getTweetCountsPerFrequency,time,tweet3,minute
From: https://www.cnblogs.com/grandyang/p/17480072.html

相关文章

  • lower_bound upper_bound in cpp
    upper_boundReturnsaniteratorpointingtothefirstelementintherange[first,last)whichcomparesgreaterthanval.ReturnvalueAniteratortotheupperboundpositionforvalintherange.Ifnoelementintherangecomparesgreaterthanval,the......
  • 基于 hugo 和 papermod 主题搭建自己的博客
    部署博客到vercelFreeNom申请域名首先,梯子最好选择美国的,并且freenom选择地址时最好与ip所在州可以对应得上;进入FreeNom,输入zwyb.tk,然后点击检查可用性,这里要记得输入后缀,能避免点击现在获取显示不可用的问题。如下图所示:Cloudfare管理域名cloudfare添加站点zwyyy456.ml,然......
  • 为 papermod 主题添加 Latex 支持
    stepstofollow在themes/PaperMod/layouts/partials目录下创建math.html文件,文件内容如下<linkrel="stylesheet"href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css"integrity="sha384-bYdxxUwYipFNohQlHt0bjN/LCpueqWz13HufFEV1SUatK......
  • Netflix如何通过重构视频Gatekeeper提升内容运营效率?
    Gatekeeper是Netflix的视频内容评估管理平台,可以展示视频剧集的metadata,如合同信息、字幕、标题、内容分级等。但此前,运营人员无法通过Gatekeeper实时更新剧集信息,本文将介绍新的gatekeeper架构,以及因此获得的收益。 文/ DrewKoszewnik译/Johnhttps://medium.com/netflix-t......
  • 2023年6月13日,Collections集合工具类,Properties配置文件类,集合使用小结
    1.Properties配置文件类创建配置文件,DBConfig.properties在src目录下username=rootpassword=123456创建test01类packagecom.wz.properties_class;importjava.io.IOException;importjava.util.Properties;publicclasstest01{/***知识点:配置文件类propertie......
  • AtCoder Regular Contest 141 C Bracket and Permutation
    洛谷传送门AtCoder传送门考虑给出\(S\),如何求\(P,Q\)。先考虑\(P\),那我们肯定想让\(P\)的每一项都尽量往前靠。设\([1,k]\)为合法括号串,\(S_{k+1}=\texttt{)}\),那\(P\)的前\(k\)项依次为\(1\simk\),第\(k+1\)项不能为\(k+1\)了,那找到\(k+1\)之......
  • RDIFramework.NET ━ .NET快速信息化系统开发框架 V3.2 新增解压缩工具类ZipHelper
    在项目对文件进行解压缩是非常常用的功能,对文件进行压缩存储或传输可以节省流量与空间。压缩文件的格式与方法都比较多,比较常用的国际标准是zip格式。压缩与解压缩的方法也很多,在.NET2.0开始,在System.IO.Compression中微软已经给我们提供了解压缩的方法GZipStream。对于GZipSt......
  • maven-compiler-plugin build-helper-maven-plugin Maven-assembly-plugin
    三个插件都是是用干啥的maven-compiler-plugin进行源代码的编译build-helper-maven-plugin项目中添加额外的资源、源代码、构建输出目录和依赖项等Maven-assembly-plugin生成可执行jar包<build><plugins><plugin><groupId......
  • postman运行collection上传文件脚本 console报错 Form param `file`, file load error
    postman运行collection上传文件脚本console报错Formparam`file`,fileloaderror:PPERM:insecurefileaccessoutsideworkingdirectory是因为没有打开上传的文件的所在目录解决办法有两种:1)在files路径下存放你所要的测试数据2)开启允许读取工作目录外的文件......
  • Operating System Overview
    ComputerSystemOverview1.1Whatarethethreemainpurposesofanoperatingsystem?(1)Interfacebetweenthehardwareanduser;(2)managetheresourceofhardwareandsoftware;(3)abstractionofresource;1.2Listthefourstepsthatarenecessaryto......