Leetcode 1470 Solution

This article provides solution to leetcode question 1470 (tweet-counts-per-frequency)

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

Solution

class TweetCounts {
    map<std::string, map<int, int>> tweets;

public:
    TweetCounts() {
    }

    void recordTweet(string tweetName, int time) {
        tweets[tweetName][time] += 1;
    }

    vector<int> getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) {
        auto& tweetsForName = tweets[tweetName];
        int seclen = 0;

        if (freq == "minute")
            seclen = 60;
        else if (freq == "hour")
            seclen = 3600;
        else if (freq == "day")
            seclen = 86400;

        int sec_start_time = startTime;
        int sec_cnt = 0;
        vector<int> ans;

        for (auto it = tweetsForName.lower_bound(startTime); it != tweetsForName.end(); it++)
        {
            if (it->first > endTime)
                break;

            while (it->first >= sec_start_time + seclen)
            {
                ans.push_back(sec_cnt);

                sec_start_time += seclen;
                sec_cnt = 0;
            }

            sec_cnt += it->second;
        }

        while (sec_start_time <= endTime)
        {
            ans.push_back(sec_cnt);
            sec_start_time += seclen;
            sec_cnt = 0;
        }

        return ans;
    }
};

/**
 * Your TweetCounts object will be instantiated and called as such:
 * TweetCounts* obj = new TweetCounts();
 * obj->recordTweet(tweetName,time);
 * vector<int> param_2 = obj->getTweetCountsPerFrequency(freq,tweetName,startTime,endTime);
 */